Python FieldError位于/admin/-为UserProfile指定的未知字段(已添加)
我在Django中使用自定义用户模型。该模型运行良好,能够创建用户。但是当我尝试访问管理页面时,它会抛出错误Python FieldError位于/admin/-为UserProfile指定的未知字段(已添加),python,django,django-models,django-admin,django-users,Python,Django,Django Models,Django Admin,Django Users,我在Django中使用自定义用户模型。该模型运行良好,能够创建用户。但是当我尝试访问管理页面时,它会抛出错误 FieldError at /admin/ Unknown field(s) (added_on) specified for UserProfile UserProfile添加了一个属性。我想不出有什么理由可以证明这一点。如果我从admin.py文件中删除added_on属性,管理面板将工作 这是我的模特 from django.db import models from djang
FieldError at /admin/
Unknown field(s) (added_on) specified for UserProfile
UserProfile
添加了一个属性。我想不出有什么理由可以证明这一点。如果我从admin.py文件中删除added_on
属性,管理面板将工作
这是我的模特
from django.db import models
from django.contrib.auth.models import User, BaseUserManager, AbstractBaseUser
from django.conf import settings
class UserProfileManager(BaseUserManager):
def create_user(self, email, username, name, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
username=username,
name=name,
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, name, password):
user = self.create_user(email=email,
password=password,
username=username,
name=name
)
user.is_admin = True
user.save(using=self._db)
return user
class UserProfile(AbstractBaseUser):
SHOPPER = 1
TECH_ENTHU = 2
TECH_JUNKIE = 3
TECH_NINJA = 4
TECH_GURU = 5
LEVELS = (
(SHOPPER, 'Shopper'),
(TECH_ENTHU, 'Tech Enthusiast'),
(TECH_JUNKIE, 'Tech Junkie'),
(TECH_NINJA, 'Tech Ninja'),
(TECH_GURU, 'Tech Guru')
)
email = models.EmailField(max_length=255, unique=True)
username = models.CharField(max_length=100, unique=True)
name = models.CharField(max_length=255)
location = models.CharField(max_length=255, blank=True, null=True)
website = models.CharField(max_length=255, blank=True, null=True)
image_1 = models.CharField(max_length=255, blank=True, null=True)
image_2 = models.CharField(max_length=255, blank=True, null=True)
image_3 = models.CharField(max_length=255, blank=True, null=True)
points = models.PositiveIntegerField(default=0)
level = models.PositiveSmallIntegerField(choices=LEVELS, default=SHOPPER)
added_on = models.DateTimeField(auto_now_add=True)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'name']
objects = UserProfileManager()
def get_full_name(self):
return self.name
def get_short_name(self):
return self.name
def __unicode__(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
class OldUser(models.Model):
old_user_id = models.BigIntegerField()
user = models.ForeignKey(settings.AUTH_USER_MODEL)
converted = models.BooleanField(default=False)
这是我的管理员
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from users.models import UserProfile
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = UserProfile
fields = ('username', 'name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
"""A form for updating users. Includes all the fields on
the user, but replaces the password field with admin's
password hash display field.
"""
password = ReadOnlyPasswordHashField()
class Meta:
model = UserProfile
fields = ('email', 'password', 'username', 'name', 'location', 'website', 'image_1', 'image_2', 'image_3',
'points', 'level', 'added_on', 'is_active', 'is_admin')
def clean_password(self):
# Regardless of what the user provides, return the initial value.
# This is done here, rather than on the field, because the
# field does not have access to the initial value
return self.initial["password"]
class UserProfileAdmin(UserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# The fields to be used in displaying the User model.
# These override the definitions on the base UserAdmin
# that reference specific fields on auth.User.
list_display = ('email', 'username', 'name', 'points', 'level', 'is_admin')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('username', 'name', 'location', 'website', 'image_1', 'image_2', 'image_3',
'points', 'level', 'added_on')}),
('Permissions', {'fields': ('is_admin',)}),
)
# add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
# overrides get_fieldsets to use this attribute when creating a user.
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'username', 'name', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(UserProfile, UserProfileAdmin)
# Since we're not using Django's built-in permissions,
# unregister the Group model from admin.
admin.site.unregister(Group)
这是回溯
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/
Django Version: 1.6.2
Python Version: 2.7.3
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'users')
Installed Middleware:
('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 "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py" in get_response
101. resolver_match = resolver.resolve(request.path_info)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in resolve
318. for pattern in self.url_patterns:
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in url_patterns
346. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py" in urlconf_module
341. self._urlconf_module = import_module(self.urlconf_name)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module
40. __import__(name)
File "/home/jaskaran/coding/buyingiq/authentication/authentication/urls.py" in <module>
4. admin.autodiscover()
File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/__init__.py" in autodiscover
29. import_module('%s.admin' % app)
File "/usr/local/lib/python2.7/dist-packages/django/utils/importlib.py" in import_module
40. __import__(name)
File "/home/jaskaran/coding/buyingiq/authentication/users/admin.py" in <module>
36. class UserChangeForm(forms.ModelForm):
File "/usr/local/lib/python2.7/dist-packages/django/forms/models.py" in __new__
292. raise FieldError(message)
Exception Type: FieldError at /admin/
Exception Value: Unknown field(s) (added_on) specified for UserProfile
环境:
请求方法:获取
请求URL:http://127.0.0.1:8000/admin/
Django版本:1.6.2
Python版本:2.7.3
已安装的应用程序:
(“django.contrib.admin”,
“django.contrib.auth”,
“django.contrib.contenttypes”,
“django.contrib.sessions”,
“django.contrib.messages”,
“django.contrib.staticfiles”,
"用户")
已安装的中间件:
('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.xframeoptions中间件')
回溯:
get_响应中的文件“/usr/local/lib/python2.7/dist packages/django/core/handlers/base.py”
101解析程序匹配=解析程序.resolve(请求.path\u信息)
解析中的文件“/usr/local/lib/python2.7/dist packages/django/core/urlresolvers.py”
318对于self.url_模式中的模式:
url_模式中的文件“/usr/local/lib/python2.7/dist packages/django/core/urlresolvers.py”
346patterns=getattr(self.urlconf_模块,“urlpatterns”,self.urlconf_模块)
urlconf_模块中的文件“/usr/local/lib/python2.7/dist packages/django/core/urlresolvers.py”
341self.\u urlconf\u module=import\u模块(self.urlconf\u名称)
导入模块中的文件“/usr/local/lib/python2.7/dist packages/django/utils/importlib.py”
40. __导入(名称)
文件“/home/jaskaran/coding/buyingiq/authentication/authentication/url.py”
4.admin.autodiscover()
自动发现中的文件“/usr/local/lib/python2.7/dist-packages/django/contrib/admin/_-init__.py”
29导入模块(“%s.admin”%app)
导入模块中的文件“/usr/local/lib/python2.7/dist packages/django/utils/importlib.py”
40. __导入(名称)
文件“/home/jaskaran/coding/buyingiq/authentication/users/admin.py”
36类UserChangeForm(forms.ModelForm):
新文件中的“/usr/local/lib/python2.7/dist packages/django/forms/models.py”__
292raise FIELD错误(消息)
异常类型:字段错误位于/admin/
异常值:为UserProfile指定的未知字段(已添加)
您的问题是该字段上的自动\u now\u add=True
。请参见以下页面上的注释:
请注意,始终使用当前日期;它不仅仅是一个可以覆盖的默认值
及
按照当前的实施方式,设置auto\u now
或auto\u now\u add
至True
将导致字段设置editable=False
和blank=True
由于editable=False,因此不能将其包含在该表单的字段列表中(当然可以将其放入只读字段中)
如果希望该值将创建日期作为默认值,但仍允许对其进行编辑和覆盖,则应改用default
:
added_on = models.DateTimeField(default=datetime.datetime.now)
(旁注,您应该始终使用callable作为默认值,而不使用调用括号)。要使auto\u now\u add字段在管理中可见(只读),您必须将其添加到只读字段和字段中。