I
I
Ivan Zhuravlev2019-03-29 13:08:13
PostgreSQL
Ivan Zhuravlev, 2019-03-29 13:08:13

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)

First I created a form to create a new category which had two fields according to the model. Those. the slug was given by hand. I handled errors in the form for such a case as follows:
if Category.objects.filter(slug__iexact=new_slug).count():
        raise ValidationError(f'Категория "{self.cleaned_data.get("category")}" уже существует')

However, setting the slug with your hands every time is not the best choice. Therefore, a function was written gen_slugthat simply uses the Django built-in function for English-language categories slugify, and does transliteration in the case of a Russian-language category.
After I implemented this functionality, I decided to remove the slug field from the category creation form. And now naturally I get an IntegrityError when I try to create a category that is already in the database.
Can you please tell me how this error can be handled in such a way that it is displayed as an alert in the form, as I did it for a form with two fields?
Form code:
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

View code:
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 question

Ask a Question

731 491 924 answers to any question