在从表单更新数据时,出现错误 NOT NULL约束失败:accounts_user.password 。 我正在使用自定义用户模型。一切正常,但是在从管理表单更新数据时出现此错误。
modles.py
from phonenumber_field.modelfields import PhoneNumberField
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import (
BaseUserManager,
AbstractBaseUser
)
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, first_name, last_name, **extra_fields):
now = timezone.now()
if not username:
raise ValueError('User must have a username.')
else:
username = username.lower()
if not password:
raise ValueError('Password required!')
email = self.normalize_email(email)
user_obj = self.model(
username = username,
email = email,
first_name = first_name,
last_name = last_name,
#is_staff = is_staff,
#is_active = is_active,
#is_admin = is_admin,
#date_of_birth = date_of_birth,
)
user_obj.set_password(password)
user_obj.save(using = self._db)
return user_obj
def create_superuser(self, username, email, password, first_name, last_name, **extra_fields):
extra_fields.setdefault('is_staff',True)
extra_fields.setdefault('is_admin',True)
return self._create_user(
username = username,
email = email,
password = password,
first_name = first_name,
last_name = last_name,
**extra_fields
)
def create_user(self, username, email, password, first_name, last_name, **extra_fields):
extra_fields.setdefault('is_staff',True)
extra_fields.setdefault('is_admin',False)
return self._create_user(
username = username,
email = email,
password = password,
first_name = first_name,
last_name = last_name,
**extra_fields
)
def create_webuser(self, username, email, password, firstname, first_name, last_name, **extra_fields):
extra_fields.setdefault('is_staff',False)
extra_fields.setdefault('is_admin',False)
return self._create_user(
username = username,
email = email,
password = password,
first_name = first_name,
last_name = last_name
**extra_fields
)
class User(AbstractBaseUser):
GET_COLOR_CODE = (
('PI', 'PINK'),
('BL', 'BLUE'),
('RE', 'RED'),
('YL', 'YELLOW'),
('GR', 'GREEN')
)
color_code = models.CharField(max_length = 10, choices = GET_COLOR_CODE)
username = models.CharField(max_length = 33, unique = True)
first_name = models.CharField("First name of the user", max_length = 33)
last_name = models.CharField("Last name of the user", max_length = 33)
email = models.EmailField("Email of user", max_length = 255, unique = True)
phone_number = PhoneNumberField()
#date_of_birth = models.DateTimeField()
is_staff = models.BooleanField(default =True)
is_active = models.BooleanField(default = True)
is_admin = models.BooleanField(default = False)
timestamp = models.DateTimeField(auto_now_add=True)
#is_staff = models.BooleanField(default = False)def inscription(request):
object = UserManager()
USERNAME_FIELD = 'username'
REQUIRED_FIELDS = ['email','first_name','last_name'] # to create python manage.py createsuperuser
def get_username(self):
return getattr(self, self.USERNAME_FIELD)
def __str__(self):
return self.first_name
def get_full_name(self):
return self.first_name+' '+self.last_name
def get_short_name(self):
return self.first_name
def has_perm(self, perm, obj = None):
return True
def has_module_perms(self, app_label):
return True
@property
def active(self):
return self.is_active
@property
def admin(self):
return self.is_admin
@property
def staff(self):
return self.is_staff
这是我发现的回溯。
Django Version: 2.0.6
Python Version: 3.6.5
Installed Applications:
['accounts',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'phonenumber_field']
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 "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
303. return Database.Cursor.execute(self, query, params)
The above exception (NOT NULL constraint failed: accounts_user.password) was the direct cause of the following exception:
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/admin/options.py" in wrapper
575. return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/admin/sites.py" in inner
223. return view(request, *args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/admin/options.py" in change_view
1557. return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/utils/decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/utils/decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/admin/options.py" in changeform_view
1451. return self._changeform_view(request, object_id, form_url, extra_context)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/admin/options.py" in _changeform_view
1491. self.save_model(request, new_object, form, not add)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/admin/options.py" in save_model
1027. obj.save()
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/contrib/auth/base_user.py" in save
73. super().save(*args, **kwargs)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/base.py" in save
729. force_update=force_update, update_fields=update_fields)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/base.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/base.py" in _save_table
823. forced_update)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/base.py" in _do_update
872. return filtered._update(values) > 0
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/query.py" in _update
709. return query.get_compiler(self.db).execute_sql(CURSOR)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1379. cursor = super().execute_sql(result_type)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/models/sql/compiler.py" in execute_sql
1068. cursor.execute(sql, params)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
100. return super().execute(sql, params)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/utils.py" in execute
68. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute_with_wrappers
77. return executor(sql, params, many, context)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/utils.py" in _execute
85. return self.cursor.execute(sql, params)
File "/home/dev/.virtualenv/django/lib/python3.6/site-packages/django/db/backends/sqlite3/base.py" in execute
303. return Database.Cursor.execute(self, query, params)
Exception Type: IntegrityError at /locdev/accounts/user/11/change/
Exception Value: NOT NULL constraint failed: accounts_user.password
我不明白问题是什么。请任何人都可以帮助我!
答案 0 :(得分:0)
我认为您没有迁移模型。
return str(url_for('hi', var='Hello', var2='xyz')
然后将此代码添加到settings.py文件中:
python manage.py makemigrations
python manage.py migrate
myApp 是您在其中编写用户模型的应用的名称。
答案 1 :(得分:0)
我认为发生此错误是因为在从管理面板更新您的数据时,django 将密码字段设置为 null 并打破了密码字段的非空约束。
您可以将其添加到您的 UserChangeForm 中,您可以在其中定义从 Modelform 继承的表单。
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = MyUser
fields=('username','email', 'firstname','lastname', 'is_active','is_admin')
def clean_password(self):
return self.initial['password']
这会为更新的数据设置相同的初始密码。