简体   繁体   English

如何在Django中删除字段并为ModelForm设置默认值?

[英]How to remove a field and set default value for a ModelForm in Django?

I have a ModelForm in my forms.py as follows: 我的forms.py中有一个ModelForm,如下所示:

class ChoiceForm(forms.ModelForm):
class Meta:
    model = Choice
    fields = ['choice_text', 'is_choice_correct']
    labels = {
        'choice_text': "",
        'is_choice_correct': ""
    }
    widgets = {
        "choice_text": forms.Textarea(),
        "is_choice_correct": "",
    }

Based on some conditions, I would like the is_correct_field , a boolean field to not display in the form and set default value for the field (because it is required) so that when I write form.save() in my views, there occurs no error. 根据某些条件,我希望is_correct_field (一个布尔型字段)不显示在表单中,并为该字段设置默认值(因为这是必需的),以便在视图中编写form.save()时不会出现错误。

However, I don't want to hide the form field. 但是,我不想隐藏表单字段。 To make it more clear, here's what I want to say. 更清楚地说,这就是我想说的。 I submit the form with only choice_text in my form. 我提交的表单中仅choice_text The form does not contain the field is_choice_correct , either hidden or displayed. 表单不包含隐藏或显示的字段is_choice_correct When I save the form with form.save(), I want the is_choice_correct to be True. 当我使用form.save()保存表单时,我希望is_choice_correct为True。

Why not declare the default value for is_choice_correct on the model itself? 为什么不在模型本身上声明is_choice_correct的默认值?

class Choice(models.Model):
    is_choice_correct = models.BooleanField(default=True)

Then exclude the field from the form as Exprator shows. 然后,如Exprator所示,从表单中排除该字段。 If you want to include the field on the form only under some conditions, you can edit the form's .fields during __init__ . 如果只想在某些情况下将字段包括在表单中,则可以在__init__期间编辑表单的.fields

class ChoiceForm(forms.ModelForm):

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs) # important, call super() first or the form has no .fields attribute
        if my_condition:
            self.fields['is_choice_correct'] = Choice._meta.get_field('is_choice_correct').formfield()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM