复选框未出现在ModelForm中

时间:2019-04-12 01:28:23

标签: django django-models modelform

我创建了一个汉堡模型,该模型可以在汉堡上具有附加功能和浇头。因此,我创建了两个名为Topping和Extra的其他类,这些类具有可用的选择。但是,当我运行该程序时,“打顶”和“额外”复选框没有出现

我尝试在汉堡类中添加浇头和附加内容,并显示了复选框,但是在勾选复选框后提交表单时,这就产生了问题。所以我尝试创建nex类,并通过Burger类在ManyToMany关系中引用它们

这是我的model.py代码:

BURGER_CHOICES = (("AFBB", "Aurion's Famous Beef Burger"), ("AIPB", 
"Aurion's Infamous Pork Burger"), ("AULB", "Aurion's Undiscovered Lamb 
Burger"), ("POG", "Pureed Otter Giblets"))
BUN_CHOICES = (("WHITE","White Bread"), ("RYE","Rye"), ("TPOODLE", "Teacup 
Poodles"), ("AFOSSIL","Ammonite Fossils"))
TOPPING_CHOICES = (("CHEESE", "Cheese", ), ("LETTUCE", "Lettuce"), 
("TOMATOE", "Tomatoe"), ("ONION", "Onion"), ("WSHAVE", "Wood Shavings"))
SAUCES_CHOICES = (("OZTS", "Our Zesty Barbaque Sauce"), ("SEZBS", "Someone 
Elses Zesty Barbaque Sauce"), ("VS", "Varmint Squeezings"))
EXTRAS_CHOICES = (("P", "Pinapple"), ("SG", "Soylent Green"), ("SB", 
"Soylent Blue"), ("MWS", "More Wood Shavings"))


class Burger(models.Model):
    burger = models.CharField(max_length=50,choices=BURGER_CHOICES )
    bun = models.CharField(max_length=50, choices=BUN_CHOICES)
    toppings = models.ManyToManyField('Topping')
    sauces = models.CharField(max_length=60, choices=SAUCES_CHOICES)
    extras = models.ManyToManyField('Extra')

    def __str__(self):
        return self.burger

class Topping(models.Model):
    topping = models.CharField(blank=True, max_length=60, 
choices=TOPPING_CHOICES)

    def __str__(self):
        return self.topping

class Extra(models.Model):
    extra = models.CharField(blank=True, max_length=60, 
choices=EXTRAS_CHOICES)

    def __str__(self):
        return self.extra


class BurgerForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(BurgerForm, self).__init__(*args, **kwargs)
        self.fields['toppings'].widget = forms.CheckboxSelectMultiple()
        for field_name in self.fields:
            field = self.fields.get(field_name)
            if field and isinstance(field , forms.TypedChoiceField):
                field.choices = field.choices[1:]
        self.fields['extras'].widget = forms.CheckboxSelectMultiple()

    class Meta:
        model = Burger
        fields = ['burger', 'bun', 'toppings', 'sauces', 'extras']

0 个答案:

没有答案