Search code examples
python-3.xdjangoslug

Django forms.ModelForm slugfield db_index=True


I have a slug field in my Model with db_index=True:

class Student(models.Model):
    ...
    slug = models.SlugField(max_length=100, db_index=True)

When a new record is added through my form, i want slug field to be filled with slugified text that I have coded in my model save() method. However, this never happens as I am stuck at form field level validation.

I have tried many options like clean(), clean_field() etc but all of them runs only after slug field has something entered.


Solution

  • You must allow blank values to be entered on the form using blank=True. You will also generally want to use unique=True instead of db_index=True for a slug field:

    slug = models.SlugField(max_length=100, blank=True, unique=True)
    

    Note that unique implies db_index.