提交表单时,Django is_valid() 会抛出 ValueError 。不知道为什么

发布于 2024-10-25 02:04:22 字数 1995 浏览 3 评论 0原文

以下代码基于模型 Post 创建一个表单。我面临的问题是,如果我删除 if post_form.is_valid():,表单永远不会验证,并给出ValueError数据未验证查看。

但是,如果我保留如下所示的代码,即保留 if post_form.is_valid(): 检查,那么它总是失败并执行 else 块。

我试图在我的模型中保存用户,它是 Django Auth 的外键,结果发现我什至无法克服这个 vlaidation 错误。

任何帮助将不胜感激。谢谢。

#----------------------------Model-------------------------------------- 
class Post (models.Model): 
    name = models.CharField(max_length=1000, help_text="required, name of the post") 
    user = models.ForeignKey(User, unique=False, help_text="user this post belongs to") 

    def __unicode__(self): 
        return self.name 

class PostForm(ModelForm): 
    class Meta: 
            model = Post 
#----------------------------./Model--------------------------------------

#----------------------------View-------------------------------------- 
@login_required 
def create_post (request): 
    if request.method == 'POST': 
        post_form = PostForm(request.POST) 
        if post_form.is_valid(): 
            post.save() 
            return render_to_response('home.html') 
        else: 
            return HttpResponse('not working') 
    else: 
        post_form = PostForm() 
        return render_to_response('create.html', {'post_form':post_form }) 
#----------------------------./View--------------------------------------

#----------------------------./Template--------------------------------------
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>home</title>
</head>
<body>
<form method="POST" action='.'>{% csrf_token %}
    <p>{{post_form.name.label_tag}}</p>
    <p>{{post_form.name}}</p>
        <p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>
#----------------------------./Template--------------------------------------

The following code creates a form based on a model, Post. Problem I am facing is that the form never validates and gives ValueError that data did not validate if I remove the if post_form.is_valid(): check.

However, if I keep the code as shown below, that is, I keep the if post_form.is_valid(): check, then it always fails and the else block is executed.

I was trying to save the User, which is a ForeignKey to Django's Auth, in my model and it turns out I cannot even get past this vlaidation error.

Any help will be appreciated. Thanks.

#----------------------------Model-------------------------------------- 
class Post (models.Model): 
    name = models.CharField(max_length=1000, help_text="required, name of the post") 
    user = models.ForeignKey(User, unique=False, help_text="user this post belongs to") 

    def __unicode__(self): 
        return self.name 

class PostForm(ModelForm): 
    class Meta: 
            model = Post 
#----------------------------./Model--------------------------------------

#----------------------------View-------------------------------------- 
@login_required 
def create_post (request): 
    if request.method == 'POST': 
        post_form = PostForm(request.POST) 
        if post_form.is_valid(): 
            post.save() 
            return render_to_response('home.html') 
        else: 
            return HttpResponse('not working') 
    else: 
        post_form = PostForm() 
        return render_to_response('create.html', {'post_form':post_form }) 
#----------------------------./View--------------------------------------

#----------------------------./Template--------------------------------------
<html lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>home</title>
</head>
<body>
<form method="POST" action='.'>{% csrf_token %}
    <p>{{post_form.name.label_tag}}</p>
    <p>{{post_form.name}}</p>
        <p><input type="submit" value="Submit"/></p>
</form>
</body>
</html>
#----------------------------./Template--------------------------------------

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

倒数 2024-11-01 02:04:22

在您的另一篇文章中,您尝试自动插入 user 字段,这可能意味着您的模板中没有显示 user 字段。

如果您打算插入用户,请排除它。

class PostForm(ModelForm): 
    class Meta: 
            model = Post 
            exclude = ('user',) # exclude this

if request.method == 'POST': 
    post_form = PostForm(request.POST) 
    if post_form.is_valid(): 
        post = post.save(commit=False) 
        post.user = request.user
        post.save()  # now post has a user, and can actually be saved.
        return render_to_response('home.html') 

In your other post, you were trying to automatically insert the user field, which probably means you don't have a user field displayed in the template.

Exclude it if you plan to insert the user anyways.

class PostForm(ModelForm): 
    class Meta: 
            model = Post 
            exclude = ('user',) # exclude this

if request.method == 'POST': 
    post_form = PostForm(request.POST) 
    if post_form.is_valid(): 
        post = post.save(commit=False) 
        post.user = request.user
        post.save()  # now post has a user, and can actually be saved.
        return render_to_response('home.html') 
等风来 2024-11-01 02:04:22

它显示无效,因为表单无效。据推测提交表格的人没有填写必填字段。如果您显示 form.errors 的值,您就会明白原因。

或者,虽然我们必须猜测,因为您没有显示模板,但您没有在模板本身中包含所有必填字段,因此表单永远不会有效。

删除第一个 else 子句及其 HttpResponse。然后,视图将默认再次显示表单,但有错误。

It shows not valid, because the form is not valid. Presumably whoever submitted the form did not fill in the required fields. If you display the value of form.errors you will see why.

Alternatively, although we have to guess because you have not shown the template, you have not included all the required fields in the template itself, therefore the form will never be valid.

Remove the first else clause with its HttpResponse. The view will then default to showing the form again, complete with errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文