How to handle IntegrityError in Django form?

Hello. Learn Django 2 (write first draft on it) and I am having a problem that probably is easy to solve, but the gugleniya not yet helped.

The problem is the following: there is a model responsible for a 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)

First, I created a form to create a new category, which had two fields in accordance with the model. I.e. slug asked hands. Error in form for such a case I handled in the following way:
if Category.objects.filter(slug__iexact=new_slug).count():
 raise ValidationError(Category f "{self.cleaned_data.get("category")}" already exists')

However, each time ask slug hands - not the best choice. Therefore was written the function of gen_slug, which for English-speaking categories just uses the built-in Django function slugify, and in the case of Russian-speaking category makes transleithania.

After I implemented this functionality, I decided to remove slug field from the form, create category. And now, of course, get a IntegrityError when trying to create a category that already exists in the database.

Please tell me how this error can be treated so that it displays an alert in the form of how I implemented a form with two fields?

Form code:
class CategoryForm(forms.ModelForm):

 class Meta:
 model = Category
 fields = ['category'] # the original version have also been a '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 may not have the value "create"!')
 if Category.objects.filter(slug__iexact=new_slug).count():
 raise ValidationError(Category f "{self.cleaned_data.get("category")}" already exists')
 return new_slug

Code view function:
class CategoryCreate(View):
 def get(self, request):
 form = CategoryForm()
 data = {'title': 'Create new category',
 '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 =
 return redirect(new_cat)
March 19th 20 at 09:09
0 answer

Find more questions by tags DjangoPostgreSQL