Selena
Selena

Reputation: 41

Why is "Field is required" appearing for every field after submitting a valid form in django?

When I submit the form, it displays a blank form and says "field is required" for each field. But when I fill it again and submit, it works. Any reason why it does this?

def forum_modules(request):
    if request.method == 'POST':
        pform = PostForm(data=request.POST, prefix='PostForm')
        if pform.is_valid():
            new_post = pform.save(commit=False)
            new_post.user = request.user
            new_post.save()

            return HttpResponse("Post was successfully added")

    else:
        pform = PostForm()


    return render(request, 'forum/forum_modules.html', 'pform': pform})

PostForm :

class PostForm(ModelForm):
    class Meta:
        model = Post
        fields = ['title', 'body']
        exclude = ['user']

Post model:

class Post(models.Model):

    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, )
    title = models.CharField(max_length=100)
    body = models.TextField()
    date = models.DateField(auto_now_add=True, blank=True)
    likes = models.IntegerField(default=0, blank=True)

    def __str__(self):
        return self.title

Upvotes: 0

Views: 62

Answers (2)

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

The prefix parameter in Form, either use it in both GET and POST form creations or don't use it in both the forms.

def forum_modules(request):
    if request.method == 'POST':
        pform = PostForm(data=request.POST)
        if pform.is_valid():
            new_post = pform.save(commit=False)
            new_post.user = request.user
            new_post.save()
            return HttpResponse("Post was successfully added")
    else:
        pform = PostForm()
    return render(request, 'forum/forum_modules.html', 'pform': pform})

Upvotes: 1

Daniel Roseman
Daniel Roseman

Reputation: 599926

You're using a prefix when you instantiate on POST, but not on GET. That means that the fields don't match up; on submission, Django is expecting field names that begin with "PostForm", but it doesn't output those in the form to begin with.

I don't know why you're using a prefix at all - it doesn't seem to be required here - but if you do, you need to use it in both the POST and GET blocks when you instantiate the form.

Upvotes: 1

Related Questions