Search code examples
djangodjango-formsvalidationerror

Django is_valid() throws ValueError when submitting a form. Not sure why


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--------------------------------------

Solution

  • 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')