如何解决导致外键约束失败的IntegrityError

时间:2019-02-05 10:35:21

标签: django django-models django-forms django-modeladmin

当尝试在Admin中更新/添加/删除用户时遇到此错误。

我真的不知道什么在引用我的模型,这导致外键约束失败。

下面是model.pyforms.pyadmin.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'

1 个答案:

答案 0 :(得分:0)

我认为这必须是因为db中已经有一个实际的表,该表未链接到其他表,这可能会导致此错误。

从主文件夹中删除所有迁移(只需保留 init .py)并删除db.sqllite3文件。

Ran进行了迁移,然后再次迁移,这一次它起作用了。

需要再次创建表,并确保它们相互链接,否则在保存期间将失败。