why i cant save m2m relationships in Django 3 - django

recently i have upgrade and app to django 3, and i'm using a many to many relationship to define the people i want to send and email, in this way:
class Contact(Master):
name = models.CharField(max_length=100, blank=True, null=True, verbose_name=_('name'))
email = models.EmailField(verbose_name=_("Email"), max_length=70, db_index=True, unique=True)
class Meta:
verbose_name = _("contact")
verbose_name_plural = _("contacts")
def __str__(self):
return "{} - {}".format(self.name, self.email)
class Newsletter(Master):
template = models.CharField(verbose_name="template",max_length=100,null=True,blank=True)
subject = models.CharField(max_length=100,null=False)
text_content = models.TextField(blank=True,null=True)
send = models.BooleanField(db_index=True,default=True)
contacts = models.ManyToManyField('contacts.Contact', blank=True, related_name="contacts", verbose_name=_('contacts'))
i make all the migrations and everything looks normal, but when i try to add contacts to the newsletter, via "admin" or "shell" it shows this error:
ProgrammingError at /es/admin/contacts/newsletter/4/change/
syntax error at or near "ON"
LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC...
the complete traceback error shows this
Traceback (most recent call last):
File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.SyntaxError: syntax error at or near "ON"
LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/beren5000/lib/python3.8/django/db/models/fields/related_descriptors.py", line 944, in add
self._add_items(
File "/home/beren5000/lib/python3.8/django/db/models/fields/related_descriptors.py", line 1123, in _add_items
self.through._default_manager.using(db).bulk_create([
File "/home/beren5000/lib/python3.8/django/db/models/query.py", line 492, in bulk_create
returned_columns = self._batched_insert(
File "/home/beren5000/lib/python3.8/django/db/models/query.py", line 1230, in _batched_insert
self._insert(item, fields=fields, using=self.db, ignore_conflicts=ignore_conflicts)
File "/home/beren5000/lib/python3.8/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/home/beren5000/lib/python3.8/django/db/models/sql/compiler.py", line 1384, in execute_sql
cursor.execute(sql, params)
File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/home/beren5000/lib/python3.8/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/beren5000/lib/python3.8/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: syntax error at or near "ON"
LINE 1: ... ("newsletter_id", "contact_id") VALUES (4, 1861) ON CONFLIC...
it seems to be an error or something in the psycopg2, but i had never clash with an error like this, the version of psycopg2 is psycopg2==2.8.4
thanks for your help

django 3 drop support for postgres 9.4
https://docs.djangoproject.com/en/3.0/releases/3.0/#dropped-support-for-postgresql-9-4

You need to change in i give line because the no reference assign if we pass in string format we need to pass as name of the model
class Newsletter(Master):
...
contacts = models.ManyToManyField(Contact, blank=True, related_name="contacts", verbose_name=_('contacts')) # change here
You need to assign Contact instead of 'contact.Contact'
don't forgot makemigrations and migrate command
if it's work let me know

Related

Heroku deployment of django project causing: Exception Type: ProgrammingError [duplicate]

This question already has answers here:
Django: ProgrammingError relation does not exists
(2 answers)
Relation does not exist - Django & Postgres
(3 answers)
Django on Heroku: relation does not exist
(5 answers)
Closed last month.
I have tested this locally and it works fine. When I deploy to Heroku it deploys fine and serves the home page. Though When I try to sign up and create a new user I get a Internal 500 error and get the following error message.
Traceback (most recent call last):
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
The above exception (relation "accounts_customuser" does not exist
LINE 1: SELECT 1 AS "a" FROM "accounts_customuser" WHERE "accounts_c...
^
) was the direct cause of the following exception:
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
response = get_response(request)
File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 103, in view
return self.dispatch(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/base.py", line 142, in dispatch
return handler(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/edit.py", line 184, in post
return super().post(request, *args, **kwargs)
File "/app/.heroku/python/lib/python3.10/site-packages/django/views/generic/edit.py", line 152, in post
if form.is_valid():
File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 205, in is_valid
return self.is_bound and not self.errors
File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 200, in errors
self.full_clean()
File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/forms.py", line 439, in full_clean
self._post_clean()
File "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/auth/forms.py", line 129, in _post_clean
super()._post_clean()
File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/models.py", line 498, in _post_clean
self.validate_unique()
File "/app/.heroku/python/lib/python3.10/site-packages/django/forms/models.py", line 507, in validate_unique
self.instance.validate_unique(exclude=exclude)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1226, in validate_unique
errors = self._perform_unique_checks(unique_checks)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/base.py", line 1336, in _perform_unique_checks
if qs.exists():
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 1225, in exists
return self.query.has_results(using=self.db)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/query.py", line 592, in has_results
return compiler.has_results()
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1363, in has_results
return bool(self.execute_sql(SINGLE))
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1395, in execute_sql
cursor.execute(sql, params)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute
with self.db.wrap_database_errors:
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
Exception Type: ProgrammingError at /accounts/signup/
Exception Value: relation "accounts_customuser" does not exist
LINE 1: SELECT 1 AS "a" FROM "accounts_customuser" WHERE "accounts_c...
Custom User Model
class CustomUser(AbstractUser):
age = models.PositiveBigIntegerField(null=True, blank=True)
business_name = models.CharField(null=True, blank=True, max_length=500)
first_name = models.CharField(null=True, blank=True, max_length=500)
last_name = models.CharField(null=True, blank=True, max_length=500)
Settings.py
AUTH_USER_MODEL = 'accounts.CustomUser'
Locally I have been testing using sqllite though I am using postgresql in heroku. I have set environment variables and it seems to be working upon deployment.
env = Env()
env.read_env()
...
DATABASES = {
'default': env.dj_db_url("DATABASE_URL")
}
Did you remember to make migrations and migrate?
heroku run python manage.py makemigrations and
heroku run python manage.py migrate

ProgrammingError at column "" does not exist

I added a custom extension to djangos User model and now I'm getting this error on my localhost url:
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column users_account.birthday does not exist
LINE 1: ... "users_account"."id", "users_account"."user_id", "users_acc...
^
Furthermore, when I tried to migrate my changes I got this error in the terminal:
Operations to perform:
Apply all migrations: admin, auth, chaburah, contenttypes, sessions, taggit, users
Running migrations:
Applying users.0002_alter_account_birthday...Traceback (most recent call last):
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
psycopg2.errors.UndefinedColumn: column "birthday" does not exist
LINE 1: ..._account" ALTER COLUMN "birthday" TYPE date USING "birthday"...
^
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/almoni/Desktop/Code/my_chaburah/manage.py", line 22, in <module>
main()
File "/Users/almoni/Desktop/Code/my_chaburah/manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line
utility.execute()
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 414, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 460, in execute
output = self.handle(*args, **options)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/base.py", line 98, in wrapped
res = handle_func(*args, **kwargs)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/core/management/commands/migrate.py", line 290, in handle
post_migrate_state = executor.migrate(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 131, in migrate
state = self._migrate_all_forwards(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 163, in _migrate_all_forwards
state = self.apply_migration(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/executor.py", line 248, in apply_migration
state = migration.apply(state, schema_editor)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/migration.py", line 131, in apply
operation.database_forwards(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/migrations/operations/fields.py", line 235, in database_forwards
schema_editor.alter_field(from_model, from_field, to_field)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 747, in alter_field
self._alter_field(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/postgresql/schema.py", line 231, in _alter_field
super()._alter_field(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 963, in _alter_field
self.execute(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/base/schema.py", line 192, in execute
cursor.execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 103, in execute
return super().execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 67, in execute
return self._execute_with_wrappers(
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 80, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/utils.py", line 91, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/almoni/.local/share/virtualenvs/my_chaburah-AiCSV-sC/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: column "birthday" does not exist
LINE 1: ..._account" ALTER COLUMN "birthday" TYPE date USING "birthday"...
It only appears when I try to either edit an existing User or create a new one.
models.py:
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birthday = models.DateTimeField(blank=True, null=True)
def __str__(self):
return self.user
admin.py:
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class CustomUserAdmin(UserAdmin):
inlines = (AccountInline,)
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
My original guess was the error was due to the fact that my existing Users have no birthday but that doesn't explain why I can't create a new User. Which makes me think I am unaware of what the actual problem is.
I'm newish to django/SQl so I don't really understand the error itself.
You forgot about:
python manage.py makemigrations
# and/or
python manage.py migrate
If error still occurs - delete the database, create new and then run above commands. If got still same error - delete the database and all migration files and then run the commands.
PS You probably want DateField not DateTimeField for birthday storage :)

How to resolve this "Invalid default value for a django.models field error"?

I am creating a student model which records homework details of a student. It works in a way that student has been given work to do at home with some deadlines of days or hours. When I migrate, I get this error I am getting this error
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 76, in _execute_with_wrappers
return executor(sql, params, many, context)
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\django\db\backends\mysql\base.py", line 73, in execute
return self.cursor.execute(query, args)
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 206, in execute
res = self._query(query)
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\cursors.py", line 319, in _query
db.query(q)
File "C:\Users\Lenovo\Documents\GitHub\All-in-one-project\ven\lib\site-packages\MySQLdb\connections.py", line 254, in query
_mysql.connection.query(self, query)
django.db.utils.OperationalError: (1067, "Invalid default value for 'deadline_type'")
for my this model
class WorkHour(models.Model):
DAYS= 'D'
HOURS= 'H'
STATUS = [
('D', 'Days'),
('H', 'Hours')
]
student= models.ForeignKey(Student, on_delete=models.CASCADE)
date= models.DateField(verbose_name='Date')
deadline_type= models.CharField(max_length=256,choices=STATUS,default= DAYS, verbose_name= "Days/Hours")
deadline_time = models.IntegerField(verbose_name='Deadline',default=1)
either I add default value in deadline_type, It gives me the above error. I have done the same thing in my other models too. I din;t know what I am doing wrong here.
You cannot have DAYS= 'D' as default, because it's not tuple. Change the field to that:
deadline_type= models.CharField(max_length=16, choices=STATUS, default=STATUS[0], verbose_name="Days/Hours")
In that way you can delete DAYS= 'D' HOURS= 'H' and default value will be always the first tuple from STATUS.

Django: Trying to make Users migration with a self-referential default value

I'm trying to set a default value on a field I added to my User model, but I'm having to do a lot of acrobativs to make it work.
I want to add an 'identifier' SlugField with a default value defined in a function, like so:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
if not User.objects.filter(identifier=identifier).exists():
return identifier
class User(AbstractUser):
identifier = models.SlugField(default=create_identifier, max_length=16)
def __str__(self):
return self.username
This exact scenario works fine on a different (not User) nodel class, but when I try to run migrations with this code for User, I get:
Traceback (most recent call last):
File "manage.py", line 29, in <module>
execute_from_command_line(sys.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
utility.execute()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 332, in execute
self.check()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 364, in check
include_deployment_checks=include_deployment_checks,
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks
issues.extend(super()._run_checks(**kwargs))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/management/base.py", line 351, in _run_checks
return checks.run_checks(**kwargs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/core/checks/registry.py", line 73, in run_checks
new_errors = check(app_configs=app_configs)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/contrib/auth/checks.py", line 74, in check_user_model
if isinstance(cls().is_anonymous, MethodType):
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/base.py", line 469, in __init__
val = field.get_default()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
return self._get_default()
File "/home/myprojectname/myprojectname/myprojectname/users/models.py", line 34, in create_identifier
if not User.objects.filter(identifier=identifier).exists():
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/query.py", line 715, in exists
return self.query.has_results(using=self.db)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/query.py", line 509, in has_results
return compiler.has_results()
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1037, in has_results
return bool(self.execute_sql(SINGLE))
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1068, in execute_sql
cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/myprojectname/.local/share/virtualenvs/myprojectname-Uef4Bstr/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "users_user" does not exist
LINE 1: SELECT (1) AS "a" FROM "users_user" WHERE "users_user"."iden...
I have to manually modify the migrations as such:
migrations.CreateModel(
name='User',
fields=[
...
('identifier', models.SlugField(default='', max_length=16)),
...
),
migrations.AlterField(
model_name='user',
name='identifier',
field=models.SlugField(default=myprojectname.users.models.create_identifier, max_length=16),
),
And then if I initially set default='' in the models.py and run migrations it works, and I can change back to default=create_identifier after the fact.
class User(AbstractUser):
identifier = models.SlugField(default='', max_length=16)
def __str__(self):
return self.username
Is there any way I can make this work without having to go through these measures?
Edit: Would I be better off just leaving blank=True, null=True and overriding the model's save() method to change the value if the field is blank or null?
I seem to have solved the issue by modifying create_identifier to the following:
def create_identifier():
while True:
identifier = ''.join(random.SystemRandom().choice('23456789BCDFGHJKMNPQRSTVWXYZ') for _ in range(15))
try:
present = User.objects.first()
except:
present = None
if present:
if not User.objects.filter(identifier=identifier).exists():
return identifier
else:
return identifier

django - UNIQUE CONSTRAINED FAILED error

This is what my models.py looks like:
from django.db import models
from django.core.validators import RegexValidator
# Create your models here.
class Customer(models.Model):
customer_id = models.AutoField(primary_key=True,unique=True)
full_name = models.CharField(max_length=50)
user_email = models.EmailField(max_length=50)
user_pass = models.CharField(max_length=30)
def __str__(self):
return "%s" % self.full_name
class CustomerDetail(models.Model):
phone_regex = RegexValidator(regex = r'^\d{10}$', message = "Invalid format! E.g. 4088385778")
date_regex = RegexValidator(regex = r'\d{2}[-/]\d{2}[-/]\d{2}', message = "Invalid format! E.g. 05/16/91")
address = models.CharField(max_length=100)
date_of_birth = models.CharField(validators = [date_regex], max_length = 10, blank = True)
company = models.CharField(max_length=30)
home_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
work_phone = models.CharField(validators = [phone_regex], max_length = 10, blank = True)
customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE)
I added customer_id to Customer after I added the same in CustomerDetail as foreign key. Why do I still get this error after running migrate, even after I added unique=True to customer_id?
Error:
Rendering model states... DONE
Applying newuser.0003_auto_20160823_0128...Traceback (most recent call last):
File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv /lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute()
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 305, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/base.py", line 356, in execute
output = self.handle(*args, **options)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 202, in handle
targets, plan, fake=fake, fake_initial=fake_initial
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 97, in migrate
state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/executor.py", line 237, in apply_migration
state = migration.apply(state, schema_editor)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/migration.py", line 129, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/migrations/operations/fields.py", line 84, in database_forwards
field,
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 231, in add_field
self._remake_table(model, create_fields=[field])
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/schema.py", line 199, in _remake_table
self.quote_name(model._meta.db_table),
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/base/schema.py", line 112, in execute
cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/utils/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/home/krag91/Documents/djangodev/virtualenv/lib/python3.5/site-packages/django/db/backends/sqlite3/base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: UNIQUE constraint failed: newuser_customer.customer_id
It seems like you are already having some objects as per old model definitions. By default django creates a field named as id to every model in database. It can be accesses by modelName.id.
In your case I guess what happened is that you are having some objects in database with customer.id as primary as primary key. So when you changed the models and applied migrations, existing objects are checked and another unique field is tried to added as a primary key. Here the workaround is to delete all the existing objects after removing the customer_id field and then try recreating the field and run migrations.
HTH