【发布时间】: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