首页 > 解决方案 > 如果名称以 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

标签: pythondjangopython-3.xdjango-modelsdjango-forms

解决方案


你可以覆盖__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')

推荐阅读