Я пытаюсь создать приложение списка дел в Django и хочу связать профиль пользователя с его собственным списком дел, элементами списка дел и дополнительным классом крайнего срока.
В настоящее время я пытаюсь создать своего суперпользователя с использованием createuperuser. Тем не менее, я получаю исключение в связи с тем, что мое ограничение внешнего ключа не выполнено. Ниже приведена трассировка:
File "manage.py", line 21, in <module>
main()
File "manage.py", line 17, in main
execute_from_command_line(sys.argv)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
utility.execute()
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv
self.execute(*args, **cmd_options)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute
return super().execute(*args, **options)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute
output = self.handle(*args, **options)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle
self.UserModel._default_manager.db_manager(database).create_superuser(**user_data)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/contrib/auth/models.py", line 158, in create_superuser
return self._create_user(username, email, password, **extra_fields)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/contrib/auth/models.py", line 141, in _create_user
user.save(using=self._db)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save
super().save(*args, **kwargs)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base
update_fields=update_fields, raw=raw, using=using,
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in send
for receiver in self._live_receivers(sender)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 175, in <listcomp>
for receiver in self._live_receivers(sender)
File "/Users/ganesh/dev/WebApp/WebApp/users/signals.py", line 10, in create_profile
Profile.objects.create(user=instance)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/query.py", line 433, in create
obj.save(force_insert=True, using=self.db)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save
force_update=force_update, update_fields=update_fields)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/base.py", line 784, in save_base
force_update, using, update_fields,
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/base.py", line 886, in _save_table
results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/base.py", line 925, in _do_insert
using=using, raw=raw,
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/query.py", line 1204, in _insert
return query.get_compiler(using=using).execute_sql(returning_fields)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1377, in execute_sql
cursor.execute(sql, params)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/utils.py", line 90, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/backends/utils.py", line 86, in _execute
return self.cursor.execute(sql, params)
File "/Users/ganesh/dev/WebApp/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 396, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
Вот мой models.py класс:
from django.db import models
from django.contrib.auth.models import User
import os
from django.db.models.signals import post_save
import datetime
class ToDoItem(models.Model):
item_name = models.CharField(max_length = 150)
item_type = models.CharField(max_length = 20)
item_desc = models.TextField()
class Meta:
verbose_plural_name = "ToDoItems"
def __str__(self):
return self.item_name
class ToDoList(models.Model):
all_lists = models.TextField()
item = models.ForeignKey(ToDoItem, default = 1, verbose_name = "ToDoItems",on_delete = models.SET_DEFAULT)
class Meta:
verbose_name_plural = "ToDoLists"
def __str__(self):
return self.all_lists
class Deadline(models.Model):
deadline_heading = models.CharField(max_length = 50)
deadline_desc = models.TextField()
deadline_due = models.DateTimeField("Date Due", default =datetime.date.today()+datetime.timedelta(days=7))
class Meta:
verbose_name_plural = "Deadlines"
def __str__(self):
return self.deadline_heading
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
dl = models.ForeignKey(Deadline, default = 1, verbose_name = "Deadlines", on_delete = models.SET_DEFAULT)
col_list = models.ForeignKey(ToDoList, default = 1, verbose_name = "ToDoLists", on_delete = models.SET_DEFAULT)
def __str__(self):
return f'{self.user.username} Profile'
Я понимаю, что существует некоторое расхождение между моим кодом и базой данных , Однако я не могу точно определить, в чем проблема. Может кто-нибудь указать на мою ошибку?
Я также хотел бы знать, как преодолеть эту проблему и что я могу сделать, чтобы избежать такой проблемы в будущем. Любые предложения?
Я очень ценю вашу помощь. Заранее большое спасибо.