【问题标题】:Form validation does not work. How to call clean_field methods表单验证不起作用。如何调用 clean_field 方法
【发布时间】: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


【解决方案1】:

为此,您必须考虑以下几点:

  • 您的makepost.htm 模板表单应包含enctype="multipart/form-data"
  • 正如 Exprator 所说,您需要获取帖子数据
  • 您还需要获取request.FILES 才能访问文件
  • 您应该使用form.cleaned_data['field'] 访问表单字段

记住这些,这段代码会给出你想要的结果

def makepicturepost(request):
    if request.method == 'POST':
        form = PostForm2(request.POST, request.FILES)
        if form.is_valid():
            author = form.cleaned_data['author']
            comment = form.cleaned_data['comment']
            picture = form.cleaned_data['picture']
            newpost = PicturePost(author=author, comment=comment, picture=picture)
            newpost.save()
            return HttpResponseRedirect('/')
    else:
        form = PostForm2()

    context = {
            'form': form
        }
    return render(request, 'makepost.htm', context)

【讨论】:

  • 这里有一些很好的建议。我将删除return HttpResponse('invalid form'),然后将视图的最后两行移出else: 块,这样无效的表单就会出现错误。正如 Resley 建议的那样,另一个改进是使用模型表单。
  • 我同意你的看法。当然他也可以使用模型形式
【解决方案2】:

1) 您需要使用 POST 数据初始化表单
2) 你需要使用form.cleaned_data

def makepicturepost(request):
    form = PostForm2(request.POST)
    if request.method == 'POST' and form.is_valid():
        author = form.cleaned_data['author']
        comment = form.cleaned_data['comment']
        picture = form.cleaned_data['picture']
        newpost = PicturePost(author=author, comment=comment, picture=picture)
        newpost.save()
        return HttpResponseRedirect('/')

    context = {
        "form": form
    }
    return render(request, "makepost.htm", context)

更简单的方法是使用ModelForm 并让表单在保存时为您创建一个新实例。

class PostForm2(forms.ModelForm):
    class Meta:
        model = PicturePost
        fields = ['author', 'comment', 'picture']
#  I've removed your clean methods as the the form does it for you
#  But the message may be different


def makepicturepost(request):
    form = PostForm2(request.POST)
    if request.method == 'POST' and form.is_valid():
        form.save()
        return HttpResponseRedirect('/')

    context = {
        "form": form
    }
    return render(request, "makepost.htm", context)

【讨论】:

    【解决方案3】:
    def makepicturepost(request):
        form = PostForm2(request.POST)
        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)
    

    您没有使用发布数据来检查 PostForm2 的干净方法

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-18
      • 2019-07-22
      • 2021-08-28
      • 2012-01-29
      相关资源
      最近更新 更多