Я создал пользовательскую модель пользователя, менеджер пользователя и администратора пользователя в Django 2.0. Все работает правильно, кроме случаев, когда я пытаюсь изменить атрибуты пользователя в качестве суперпользователя на странице администратора. Когда я пытаюсь что-либо изменить, я получаю
IntegrityError at /admin/home/myuser/14/change/
FOREIGN KEY constraint failed
Request Method: POST
Request URL: http://localhost:8000/admin/home/myuser/14/change/
Django Version: 2.0
Exception Type: IntegrityError
Exception Value:
FOREIGN KEY constraint failed
Я не уверен, что делаю неправильно, поскольку я даже не знал, что у моих моделей были какие-то внешние ключи. Я перепробовал все, что мог придумать.
models.py:
class UserManager(BaseUserManager):
use_in_migrations = True
def _create_user(self, email, name, organization, password, **extra_fields):
if not all([email, name, organization, password]):
raise ValueError("All fields are required")
email = self.normalize_email(email)
user = self.model(email=email, name=name, organization=organization, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, name, organization, password=None, **extra_fields):
extra_fields.setdefault("is_staff", False)
return self._create_user(email=email, name=name, organization=organization, password=password, **extra_fields)
def create_superuser(self, email, name, organization, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
#extra_fields.setdefault("is_admin", True)
extra_fields.setdefault("is_superuser", True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
return self._create_user(email, name, organization, password, **extra_fields)
class MyUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(_('email address'), unique=True)
name = models.CharField(max_length=40)
organization = models.CharField(max_length=100)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
can_use_monsoon = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name', 'organization']
#REQUIRED_FIELDS = []
objects = UserManager()
class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')
admin.py:
class MyUserChangeForm(UserChangeForm):
class Meta(UserChangeForm.Meta):
model=MyUser
fields = ('email', 'name', 'organization', 'can_use_monsoon')
@admin.register(MyUser)
class MyUserAdmin(admin.ModelAdmin):
model = MyUser
add_form_template = 'admin/auth/user/add_form.html'
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal info'), {'fields': ('name', 'organization')}),
(_('Permissions'), {'fields': ('can_use_monsoon',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2'),
}),
)
form = MyUserChangeForm
list_display = ('email', 'name', 'organization')
list_filter = ('can_use_monsoon', 'is_staff', 'is_superuser', 'groups')
search_fields = ('email', 'name', 'organization')
ordering = ('email', 'name', 'organization')
filter_horizontal = ('groups', 'user_permissions',)
Я изменил AUTH_USER_MODEL в settings.py, чтобы он указывал на соответствующую модель. Я также сделал все миграции. Я даже пытался очистить базу данных и удалить файлы миграции, но не повезло. Есть похожий вопрос здесь , но я пробовал решения, и они не помогают. Любая помощь с благодарностью.
Вот весь след:
Environment:
Request Method: POST
Request URL: http://localhost:8000/admin/home/myuser/18/change/
Django Version: 2.0
Python Version: 3.6.4
Installed Applications:
['home',
'config',
'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\joshu\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\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner
35. response = get_response(request)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in wrapper
574. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\joshu\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\joshu\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\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\sites.py" in inner
223. return view(request, *args, **kwargs)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in change_view
1556. return self.changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "C:\Users\joshu\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\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\contrib\admin\options.py" in changeform_view
1450. return self._changeform_view(request, object_id, form_url, extra_context)
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\transaction.py" in __exit__
212. connection.commit()
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py" in commit
261. self._commit()
File "C:\Users\joshu\AppData\Local\Programs\Python\Python36\lib\site-packages\django\db\backends\base\base.py" in _commit
239. return self.connection.commit()
File "C:\Users\joshu\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\joshu\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/home/myuser/18/change/
Exception Value: FOREIGN KEY constraint failed
и информация о запросе:
Request information
USER
test@test.com
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'VO8VhCt8ICJTYmgK6e0EB2ZupXomfdPzCsqtXkYgKbR5ikVIAk0DT38bamaU79Qx'
email
'test@test.com'
name
'TestName'
organization
'TestOrg2'
_save
'Save'