web-dev-qa-db-ja.com

/ admin /のFieldError-UserProfileに指定された不明なフィールド(added_on)

Djangoでカスタムユーザーモデルを使用しています。モデルは正常に機能し、ユーザーを作成できます。しかし、管理ページにアクセスしようとすると、エラーがスローされます

FieldError at /admin/
Unknown field(s) (added_on) specified for UserProfile

UserProfileにはadded_on属性があります。これが表示される理由は考えられません。 admin.pyファイルからadded_on属性を削除すると、管理パネルが機能します。

これが私のmodels.pyです

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)

これが私のadmin.pyです

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
22
user3725362

あなたの問題はそのフィールドのauto_now_add=Trueです。 DateFieldのドキュメント に関する注記を参照してください。

現在の日付は常に使用されることに注意してください。オーバーライドできるのは単なるデフォルト値ではありません。

そして

現在実装されているように、auto_nowまたはauto_now_addTrueに設定すると、フィールドにeditable=Falseおよびblank=Trueが設定されます。

Editable = Falseであるため、そのフォームのフィールドのリストに含めることはできません(もちろん、readonly_fieldsに入れることもできます)。

値に作成日をデフォルトとして使用し、それでも編集とオーバーライドを許可する場合は、代わりにdefaultを使用する必要があります。

added_on = models.DateTimeField(default=datetime.datetime.now)

(補足として、呼び出し括弧なしで、デフォルト値には常にcallableを使用する必要があります)。

44
Daniel Roseman