我有以下表格:
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)
虽然我得到同样的错误。
还有其他事情发生吗?
答案 0 :(得分: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')