【问题标题】:excluded field in model form still required模型表单中的排除字段仍然需要
【发布时间】:2017-09-06 00:56:59
【问题描述】:

我有以下表格:

class PostForm(forms.ModelForm):
    post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES)


    class Meta:
        model = Post
        fields = ('title','desc','image','url',) 

我有以下型号:

@python_2_unicode_compatible
class Post(models.Model):  
    entity = models.ForeignKey('companies.Entity')
    title = models.CharField('Post Title', max_length=128, unique=True) 
    desc = models.TextField('Description', blank=True, null=True)
    post_type = models.IntegerField(choices=POST_CHOICES)
    image = models.ImageField('Post Image', upload_to='post', blank=True, null=True)
    url = models.URLField(max_length=255, blank=True, null=True)
    slug = models.SlugField(blank=True, null=True, unique=True)
    created_at = models.DateTimeField(auto_now_add = True)
    updated_at = models.DateTimeField(auto_now = True)

当我提交表单时,我收到错误:

post_type 字段错误:此字段为必填项。

我想在 form.is_valid 方法之后填充这个字段。

既然这个字段不在必填字段元组中,那不是必须的吗?

我也试过添加:

post_type = models.IntegerField(choices=POST_CHOICES, blank=True)

虽然我得到了同样的错误。

还有其他事情吗?

【问题讨论】:

  • 表单中需要的字段和模型中需要的字段是不同的,如果你想让post_type为null,那么添加null=True,否则你可以在调用is_valid之前填充它,这不会影响后面附加的内容,因为您显然不关心这个字段吗?

标签: django django-models django-forms


【解决方案1】:
post_type = forms.ChoiceField(widget=forms.RadioSelect(attrs={'name': 'radioInline'}), choices=POST_CHOICES, required=False)

添加required=False 就可以了


您在 models.py 中的 post_type = models.IntegerField(choices=POST_CHOICES, blank=True) 不起作用,因为您在 ModelForm 中覆盖了 post_type 字段并且没有将其设置为 required=False


如果你想post_type = models.IntegerField(choices=POST_CHOICES, blank=True) 工作:

class PostForm(forms.ModelForm):

    class Meta:
        model = Post
        fields = ('title','desc','image','url', 'post_type')

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多