我有一个隐藏字段,可以在创建文章时保存,还有另一个隐藏字段可以告诉文章状态:forms.py:
class SavedArticles(forms.ModelForm):
class Meta:
model = Article
fields =['title', 'content', 'status', 'time_created','publisher']
widgets = {
'status': forms.HiddenInput(),
'time_created': forms.HiddenInput()
}
time_created
和status
的内容将由我在后端提供:
def publish(request):
if request.method == 'POST':
article = SavedArticles(request.POST or None)
if article.is_valid():
article = article.save(commit = False)
article.status = 0 #have tried articles.data['status'] = 0
article.time_created = timezone.now() #have tried articles.data['time_created'] = 0
article.save()
return HttpResponseRedirect(reverse('mysite:home'))
我的路线很好,但每当我感觉表单已提交时,我都会收到以下错误:
(Hidden field status) This field is required.
(Hidden field time_created) This field is required.
我在做什么错误?我一整天都在尝试。
指定 ModelForm 时,如果 POST 数据中存在未在 fields
列表/元组中指定的字段,Django 将尝试根据POST,无论是否未在 ModelForm 上指定字段。
如果没有向表单类提供初始数据,并且表单输入没有值,并且模型上的字段未指定为 blank=True
,则表单验证将失败。
我是一名优秀的程序员,十分优秀!