HiveBrain v1.2.0
Get Started
← Back to all entries
debugpythondjangoMinor

Raising an error for slug unique in django

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
uniqueerrordjangoraisingslugfor

Problem

I have the following model in models.py:

class Question(models.Model):
    title = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, db_index=True, unique=True)


for which i use a generic view:

class QuestionCreate(generic.CreateView):
    model = Question
    fields = ['title', 'text']
    def form_valid(self, form):
        instance = form.save(commit=False)
        slug = slugify(form.cleaned_data['title'])
        if Question.objects.filter(slug=slug).exists():
             form.add_error("title","This Question already exist")
             return self.form_invalid(form)


The idea is to automatically create a slug from the users title to use for url, is this approach okay if i want to do this? Is the way i added the error message correct?

Solution

Edit: I didn't realize that you did not want to save the form to the database. It's obvious now, sorry. So this answer no longer applies. But why don't you try to save the actual Question object instead?

This should work, and there's no reason to change if you validated that it does work with tests.

However it would be more Pythonic to actually try saving (without commit=False), then catching the resulting django.db.IntegrityError exception. See EAFP to understand why this is more Pythonic. The happy path will be faster too since you only need to call the database once.

Context

StackExchange Code Review Q#154564, answer score: 2

Revisions (0)

No revisions yet.