Search code examples
djangovalidationerror

Why I cannot see a error message from ValidationError Django?


I have done what is written on Django Documentation and I have tried several Youtube tutorials, including Stackoverflow's advice. However, I could not make the message "Validation Error" appear on the template. When I click the button to create a post with bad_word, I redirect to the same page, the post isn't saved but the form doesn't show me the message. I tried to save in a print( form.errors ) in the view and the terminal showed the message that I want to see in the template. So I don't know what I'm doing wrong...

view.py

if request.method == "POST":
    form = PostForm(request.POST)
    if form.is_valid():
        title = form.cleaned_data['title']
        content = form.cleaned_data['content']
        username = User.objects.get(username=f"{request.user}")
        new_post = Post(user=username, title=title, content=content, datetime=timezone.now())
        new_post.writeOnChain()
        cache.expire("cache", timeout=0)
    return HttpResponseRedirect("/")
else:
    form = PostForm()
return render(request, "api/homepage.html", {'form': form, 'postList': postList})

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ('title', 'content',)

    def clean_title(self):
        title = self.cleaned_data['title']
        if "bad_word" in title:
            raise forms.ValidationError("Error")
        return title

    def clean_content(self):
        content = self.cleaned_data['content']
        if "bad_word" in content:
            raise forms.ValidationError("Error")
        return content

template

<div class="p-3 forms m-3">
    <form class="crispy" action="{% url 'homepage' %}" method="post">
         {% csrf_token %}
         {{ form|crispy }}
        <input type="submit" class="btn buttons" value="Create Post">
    </form>
</div>

terminal print

<ul class="errorlist"><li>content<ul> class="errorlist"><li>Error</li></ul> </li></ul>

Solution

  • If your form is invalid you always redirect to "/" without form information. Your return redirect needs to be indented with the rest of the "valid" form code.

    if request.method == "POST":
        form = PostForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['content']
            username = User.objects.get(username=f"{request.user}")
            new_post = Post(user=username, title=title, content=content, datetime=timezone.now())
            new_post.writeOnChain()
            cache.expire("cache", timeout=0)
            return HttpResponseRedirect("/") # this line here
    else: