【发布时间】:2017-11-14 21:55:43
【问题描述】:
我将使用表单将记录添加到 DBase。所以当request.method ='Post'和form.is_valid时,我需要将数据写入数据库。 我把这个写在我的views.py中
def makepicturepost(request):
form = PostForm2()
print('View called')
print('Request_method ' + request.method + ' Form.is_valid ' + str(form.is_valid()))
if request.method == 'POST' and form.is_valid():
author = form.author
comment = form.comment
picture = form.picture
newpost = PicturePost(author=author, comment=comment, picture=picture)
newpost.save()
return HttpResponseRedirect('/')
context = {
"form": form
}
return render(request, "makepost.htm", context)
调用form.is_valid()后要检查表单验证,所以我在forms.py中写了一些验证方法
class PostForm2(forms.Form):
author = forms.CharField(max_length=30, widget=forms.TextInput)
comment = forms.CharField(max_length=1500, widget=forms.Textarea)
picture = forms.ImageField()
def clean_author(self):
print('cleaned_author')
author = self.cleaned_data.get('author')
if not author:
raise forms.ValidationError("Autor name shouldn't be blank")
return author
def clean_comment(self):
print('cleaned_comment')
comment = self.cleaned_data.get('comment')
if not comment:
raise forms.ValidationError("Write a pair of lines as a comment")
return comment
def clean_picture(self):
print('cleaned_picture')
picture = self.cleaned_data.get('picture')
print(picture)
return picture
我打算检查图片对象以了解如何检查它是否只是一个图像。 但是我的 clean_field 方法似乎根本没有被调用。这就是我在控制台中的内容:
View called
Request_method POST Form.is_valid False
[13/Jun/2017 11:12:38] "POST /post/ HTTP/1.1" 200 788
据我了解文档,它们应该运行,但没有运行。我哪里错了?
【问题讨论】:
-
您还需要这方面的帮助吗?
-
您可以在
forms.CharField()上使用 required=True 属性来验证空值。
标签: python django django-forms