Search code examples
djangodjango-viewsdjango-formsvalidationerror

Django doesn't show ValidationError in my web-site


guys, I am beginner at Django. I watch lessons on youtube and get different results. I use Django==2.0.7 and Python==3.6.5.

I try to get error on my page, if I write not correct name of title, but I don't get it. Look at func - **def clean_title(self, *args, kwargs), I hope, you understand, what I mean. There I have "raise forms.ValidationError("Error")", but it doesn't work anymore.

forms.py

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    title = forms.CharField(label='',
                widget=forms.TextInput(attrs={"placeholder": "title"}))
    Description = forms.CharField(
                                required=False,
                                widget=forms.Textarea(
                                    attrs={
                                    "placeholder": "Your description",
                                    "class": "new-class-name two",
                                    "id": "new-class-name two",
                                    "rows": 20,
                                    'cols':120
            }
        )
    )
    Price = forms.DecimalField(initial=199.99)
    class Meta:
        model = Product
        fields = [
            'title', 
            'Description', 
            'Price'
        ]

    def clean_title(self, *args, **kwargs):
        title = self.cleaned_data.get('title')
        if "Ruslan" in title:
            return title
        else:
            raise forms.ValidationError("Error")

In forms.py I created class ProductForm and declared the fields. In my page I see it. Also I defined clean_title. I wanted to get error if I filled in wrong name of title.

views.py

    from django.shortcuts import render
    from .models import Product
    from .forms import ProductForm as CreateForm, PureDjangoForm

    def create_form(request):
    form = CreateForm(request.POST or None)
    if form.is_valid():
        form.save()
    form = CreateForm()
    context = {
        'form': form
    }
    return render(request, "create_product_form.html", context)

create_product_form.html

    {% extends 'base.html' %}

{% block content %}
<form action='.' method="POST"> {% csrf_token %}

    {{ form.as_p }}

    <input type='submit' value='Save' />
</form>
{% endblock %}

This is my file.html, it inherits any not important details from base.html.

Guys, what's wrong, help me, please, I can't understand how I can get error if name of title is not correct? I see all fields on my page and I can fill in it, but it doesn't show me errors.


Solution

  • You should not create a new form if you made one that is invalid, the view thus should look like:

    def create_form(request):
        if request.method == 'POST':
            form = CreateForm(request.POST, request.FILES)
            if form.is_valid():
                form.save()
                return redirect('name-of-some-view')
        else:
            form = CreateForm()
        context = {
            'form': form
        }
        return render(request, 'create_product_form.html', context)

    Note: In case of a successful POST request, you should make a redirect [Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.