G
G
German Lazebny2020-10-08 02:22:02
Django
German Lazebny, 2020-10-08 02:22:02

Validation errors do not appear in the form, what should I do?

I can't figure out why I'm not getting a validation error
Code examples:

views.py:

def add_news(request):
    if request.method == "POST":
        form = NewsForm(request.POST)
        if form.is_valid():
            # news = News.objects.create(**form.cleaned_data)
            news = form.save()
            return redirect(news)
    else:
        form = NewsForm()
    return render(request, 'news/add_news.html', context={'form': form})


forms.py:
from django import forms
from .models import News
import re
from django.core.exceptions import ValidationError


class NewsForm(forms.ModelForm):
    class Meta:
        model = News
        # fields = '__all__'
        fields = ['title', 'content', 'is_published', 'category']
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'category': forms.Select(attrs={'class': 'form-control'})
        }

    def clean_title(self):
        title = self.cleaned_data['title']
        if re.match(r'\d', title):
            raise ValidationError('Название не должно начинаться с цифры')
        return title


The html form itself:
<form action="{% url 'add_news' %}" method='post'>
    {% csrf_token %}

    {% for field in form %}
    <div class="form-group">
        {{ field.label_tag }}
        {{ field }}
        <div class="invalid-feedback">
            {{ field.errors }}
        </div>
    </div>
    {% endfor %}
    <button type="submit" class="btn btn-primary btn-block">Добавить новость</button>
</form>


I haven’t tried anything already, I did it through if return form.errors - not that, I played with html - nothing helped ... Who will tell me?

5f7ed5c318150922715935.png
That's what I'm talking about

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
German Lazebny, 2020-10-08
@Just_Verin_Ger

As a result, I did it through {{ form.as_p }} in the form tag in the html file, and everything was displayed as I wanted. But if I write my form without a model, I won’t be able to display it. I will look for an answer.
5f7ee03d5fcd7242726296.png

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question