为了账号安全,请及时绑定邮箱和手机立即绑定

如果名称以 A Django 开头,则取消选择

如果名称以 A Django 开头,则取消选择

繁星淼淼 2022-08-25 14:40:31
如果“人”的名称以字母“a”开头,我想删除一个选择选项:基本上,如果People.nome或(Animal.pessoa)以字母“A”开头,我想把选择(2,“GATO”)去掉。from django.db import modelsfrom django.core.validators import RegexValidatorclass 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_choicesclass 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)forms.pyclass 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
查看完整描述

1 回答

?
白衣染霜花

TA贡献1796条经验 获得超10个赞

您可以覆盖 您的 来处理逻辑。像这样:__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')


查看完整回答
反对 回复 2022-08-25
  • 1 回答
  • 0 关注
  • 156 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号