I'm learning Django from Tango with Django but I keep getting this error when I type:
python manage.py makemigrations rango
python manage.py migrate
This is the output:
django.db.utils.IntegrityError: UNIQUE constraint failed: rango_category__new.slug
Models.py:
from django.db import models
from django.template.defaultfilters import slugify
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __unicode__(self):
return self.title
The reason for this constrain could be that you didn't have any field called
slug
inCategory
class when you have initially migrated it(First Migration), and after adding this field in the model, when you ranmakemigrations
, you have set default value to something static value(i.eNone
or '' etc), and which broke the unique constrain for the Category's table's slug column in which slug should be unique but it isn't because all the entry will get that default value.To solve this, you can either drop the database and migration files and re-run
makemigrations
andmigrate
or set a unique default value like this:Edit:
According to this, modify your migration file to overcome unique constrain. For example, modify your migration file(which added the slug field to the model) like this:
I got a field with attribute unique, which was not unique [eg 2-time same value]
then
this did the trick
Did the trick. Brutal but effective. Warning! All your data in database will be lost. You will have to create superuser and so on...
What worked for me was going to the admin and changing the value of duplicate slug, before running the migrations again.
This means a slug should be unique. You may have some data in your model. You need to delete all the data in that model and you need to migrate again.
In this situation, you have two ways to fix the error;
You need to delete it from the
Django admin
site. More often than not, it may give an error when you are trying to open the model.Open command prompt
Here if you define a product manager for your model. Then you have to define a delete function. Later you should
makemigrate
,migrate
and continue with the second way