【问题标题】:Django class based View with 2 post forms returns valid unknown具有 2 个帖子表单的基于 Django 类的视图返回有效的未知数
【发布时间】:2021-06-02 06:25:29
【问题描述】:

我在 django 中有一个视图,其中 post 方法有 2 种不同类型的表单:

def post(self, request):
    tweet_form = TweetForm(request.POST, request.FILES)
    comment_form = TweetCommentForm(request.POST)
    print(request.POST['form-button'])
    if request.POST['form-button'] == 'add_tweet':
        print(tweet_form.is_valid)
        if tweet_form.is_valid():
            content = tweet_form.cleaned_data['content']
            image = tweet_form.cleaned_data['image']
            tweet = Tweet.objects.create(
                user=request.user,
                content=content,
            )
            if image != None:
                tweet.image = image
            tweet.save()
            return redirect("/home")
    if request.POST['form-button'] == 'add_comment':        
        print(comment_form.is_valid)
        if comment_form.is_valid():
            
            content = comment_form.cleaned_data['body']
            return redirect("/home")
        
    ctx = {"tweet_form": tweet_form, "comment_form": comment_form}
    return render(request, "home.html", ctx)

这两种形式具有不同的名称、值和 ID。 当我打印(tweet_form.is_valid())(comment_form.is_valid()) 时,我会收到类似的信息:

<bound method BaseForm.is_valid of <TweetForm bound=True, valid=Unknown, fields=(content;image)>>

分别适用于两种形式。 我可以以某种方式重新组织视图以处理这两种形式还是我必须有另一个视图?

问候

【问题讨论】:

    标签: python django forms


    【解决方案1】:

    您正在尝试打印方法而不是评估方法。 试试:

    print(comment_form.is_valid())
    print(tweet_form.is_valid())
    

    【讨论】:

    • 啊,你是对的。没有正确检查。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 2014-05-26
    • 1970-01-01
    • 2021-07-09
    • 2011-05-28
    • 2015-07-26
    • 2013-08-09
    相关资源
    最近更新 更多