Answer the question
In order to leave comments, you need to log in
How to properly handle IntegrityError in Django form?
Hello. I am learning Django 2 (I am writing my first project on this framework) and I have a problem that is probably easily solved, but googling has not helped yet.
The essence of the problem is as follows: there is a model responsible for the product category with the following fields:
class Category(models.Model):
category = models.CharField(max_length=80)
slug = models.SlugField(max_length=50, unique=True, blank=True)
if Category.objects.filter(slug__iexact=new_slug).count():
raise ValidationError(f'Категория "{self.cleaned_data.get("category")}" уже существует')
gen_slug
that simply uses the Django built-in function for English-language categories slugify
, and does transliteration in the case of a Russian-language category. class CategoryForm(forms.ModelForm):
class Meta:
model = Category
fields = ['category'] # в первоначальном варианте тут был еще и 'slug'
widgets = {field: forms.TextInput(attrs={'class': 'form-control'}) for field in fields}
def clean_slug(self):
new_slug = self.cleaned_data.get('slug').lower()
if new_slug == 'create':
raise ValidationError('Slug не может иметь значение "create"!')
if Category.objects.filter(slug__iexact=new_slug).count():
raise ValidationError(f'Категория "{self.cleaned_data.get("category")}" уже существует')
return new_slug
class CategoryCreate(View):
def get(self, request):
form = CategoryForm()
data = {'title': 'Создание новой категории',
'form': form,
}
return render(request, 'create_cat.html', context=data)
def post(self, request):
bound_form = CategoryForm(request.POST)
if bound_form.is_valid():
new_cat = bound_form.save()
return redirect(new_cat)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question