python - 如果名称以 A Django 开头,请取消选择
问题描述
感谢您的宝贵时间:如果人民的名字以字母“a”开头,我想取消一个选项:
基本上,如果 People.nome 或 (Animal.pessoa) 以字母 'A' 开头,我想取消选择 (2,'GATO')。有没有办法做到这一点,或者我应该尝试除了 ChoiceField 之外的另一种方法
from django.db import models
from django.core.validators import RegexValidator
class People(models.Model):
nome = models.CharField(max_length=200)
birthday_date = models.DateField()
cpf = models.CharField(max_length=11, validators=[RegexValidator(r'^\d{1,10}$')])
def __str__(self):
return '%s' % (self.nome)
def cant_have_cat(self):
field_choices = [
(1, 'CACHORRO'),
(2, 'GATO'),
(3, 'OUTRO'),
]
self.maiusculo = self.pessoa.upper
if self.maiusculo[0] == 'A':
self.tipo != 2
return field_choices
class Animal(models.Model):
pessoa = models.ForeignKey(People, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
tipo = models.IntegerField(choices=cant_have_cat)
custo = models.DecimalField(max_digits=7, decimal_places=2)
def __str__(self):
return '%s %s' % (self.pessoa, self.name)
表格.py
class AnimalForm(forms.ModelForm):
field_choices = [
(1, 'CACHORRO'),
(2, 'GATO'),
(3, 'OUTRO'),
]
name = forms.CharField(max_length=100)
tipo = forms.ChoiceField(choices=field_choices)
custo = forms.DecimalField(max_digits=7, decimal_places=2)
class Meta:
prefix = 'animal'
model = Animal
fields = ('name', 'tipo', 'custo')
def clean(self):
people_name = self.People.nome
upper = people_name.upper()
if upper[0] == 'A':
Animal.tipo != 2
解决方案
你可以覆盖__init__
你的AnimalForm
来处理逻辑。像这样的东西:
class AnimalForm(forms.ModelForm):
field_choices = [
(1, 'CACHORRO'),
(2, 'GATO'),
(3, 'OUTRO'),
]
field_choices_subset = [
(1, 'CACHORRO'),
(3, 'OUTRO'),
]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if kwargs.get("instance") and kwargs.get("instance").pessoa.nome.startswith("a"):
self.fields["tipo"].choices = field_choices_subset
name = forms.CharField(max_length=100)
tipo = forms.ChoiceField(choices=field_choices)
custo = forms.DecimalField(max_digits=7, decimal_places=2)
class Meta:
prefix = 'animal'
model = Animal
fields = ('name', 'tipo', 'custo')
推荐阅读
- c# - 使用 SpecFlow + SpecRunner 时在线程之间共享数据
- javascript - 如何通过下拉菜单更改段落标签的值
- python - 发生异常时,Python Pandoc 子进程不打印 STDOUT
- r - 如何为数据框中的每个过滤间隔创建一个函数?
- spring-boot - Spring Boot 控制应用程序的启动
- adb - 在 ADB Shell 中,PIO 没有拾取 I2C 设备
- java - 爪哇。具有一般返回类型的策略设计模式
- matlab - 通过循环复制图像不起作用
- selenium-webdriver - 如何单击具有类名和文本的div中的元素
- css - 带有 IE11 的 svg 上的 css 背景大小问题