Answer the question
In order to leave comments, you need to log in
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})
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
<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>
Answer the question
In order to leave comments, you need to log in
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question