Я столкнулся с этой ошибкой при попытке обновить / добавить / удалить пользователей в Admin.
Я действительно не знаю, что ссылается на мою модель, что вызвало сбой ограничения внешнего ключа.
Ниже приведены model.py
, forms.py
и admin.py
Ошибка
IntegrityError at /admin/signup/user/
FOREIGN KEY constraint failed
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/signup/user/
Django Version: 2.1.4
Exception Type: IntegrityError
Exception Value:
FOREIGN KEY constraint failed
Exception Location: C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py in _commit, line 239
Python Executable: C:\Users\MY PC\AppData\Local\Programs\Python\Python36\python.exe
Python Version: 3.6.5
Python Path:
['C:\\Users\\MY PC\\Documents\\Github\\Calendaring App\\meetme',
'C:\\Users\\MY PC\\AppData\\Local\\Programs\\Python\\Python36\\python36.zip',
'C:\\Users\\MY PC\\AppData\\Local\\Programs\\Python\\Python36\\DLLs',
'C:\\Users\\MY PC\\AppData\\Local\\Programs\\Python\\Python36\\lib',
'C:\\Users\\MY PC\\AppData\\Local\\Programs\\Python\\Python36',
'C:\\Users\\MY PC\\AppData\\Roaming\\Python\\Python36\\site-packages',
'C:\\Users\\MY '
'PC\\AppData\\Local\\Programs\\Python\\Python36\\lib\\site-packages']
Трассировка:
Environment:
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/signup/user/
Django Version: 2.1.4
Python Version: 3.6.5
Installed Applications:
['login.apps.LoginConfig',
'signup.apps.SignupConfig',
'homepage.apps.HomepageConfig',
'main.apps.MainConfig',
'crispy_forms',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware']
Traceback:
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = self.process_exception_by_middleware(e, request)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
124. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in wrapper
604. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py" in inner
223. return view(request, *args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in changelist_view
1717. response = self.response_action(request, queryset=cl.get_queryset(request))
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in response_action
1400. response = func(self, request, queryset)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\actions.py" in delete_selected
39. modeladmin.log_deletion(request, obj, obj_display)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in log_deletion
842. action_flag=DELETION,
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\models.py" in log_action
35. change_message=change_message,
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\manager.py" in manager_method
82. return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\query.py" in create
413. obj.save(force_insert=True, using=self.db)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py" in save
718. force_update=force_update, update_fields=update_fields)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\models\base.py" in save_base
748. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\transaction.py" in __exit__
212. connection.commit()
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py" in commit
261. self._commit()
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "C:\Users\MY PC\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
Exception Type: IntegrityError at /admin/signup/user/
Exception Value: FOREIGN KEY constraint failed
Model.py
Это моя пользовательская модель для регистрации.
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Superuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractUser):
first_name = models.CharField(max_length=35, blank=False, null=False)
last_name = models.CharField(max_length=35, blank=False, null=False)
username = None
email = models.EmailField(_('email address'), unique=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = UserManager()
forms.py
Кроме того, моя форма определена как
class SignUpForm(UserCreationForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email',)
def __init__(self, *args, **kwargs):
super(UserCreationForm, self).__init__(*args, **kwargs)
helper = self.helper = FormHelper()
layout = helper.layout = Layout()
for field_name, field in self.fields.items():
layout.append(Field(field_name, placeholder=field.label))
helper.form_show_labels = False
super(UserCreationForm, self).__init__(*args, **kwargs)
self.fields['password1'].help_text = ""
self.fields['password2'].help_text = ""
for field_name in self.fields:
field = self.fields.get(field_name)
if field:
if type(field.widget) in (forms.CharField, forms.EmailField):
field.widget = forms.CharField(attrs = {'placeholder': field.label})
class SignUpFormChangeForm(UserChangeForm):
class Meta:
model = User
fields = ('first_name', 'last_name', 'email',)
Admin.py
class MyUserAdmin(UserAdmin):
model = User
add_form = SignUpForm
form = SignUpFormChangeForm
list_display = ('email', 'first_name', 'last_name', 'is_staff')
search_fields = ('email', 'first_name', 'last_name')
ordering = ('email',)
admin.site.register(User, MyUserAdmin)
settings.py
AUTH_USER_MODEL = 'signup.User'