AttributeError'FountForm'对象没有属性'get'

时间:2014-09-30 12:35:07

标签: django python-3.x

我正在尝试通过电子邮件授权创建用户模型(使用Django 1.7 Python 3.4)。我用admin类创建了自定义用户模型。但是当我在django管理面板中尝试编辑用户实例时,我收到一个错误:

/ admin / accounts / account / 1 /的AttributeError 'AccountForm'对象没有属性'get'

我可以通过django model API无问题地修改用户数据,只有管理面板才会出现问题。 Traceback说,电子邮件领域有些不对劲,但我不知道究竟是什么。

/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/forms/widgets.py in value_from_datadict


    return attrs
def value_from_datadict(self, data, files, name):
    """
    Given a dictionary of data and this widget's name, returns the value
    of this widget. Returns None if it's not provided.
    """
    return data.get(name, None) ...
def id_for_label(self, id_):
    """
    Returns the HTML ID attribute of this Widget for use by a <label>,
    given the ID of the field. Returns None if no ID is available.

▼ Local vars
Variable    Value
name    
'email'
data    
<django.forms.widgets.AccountForm object at 0x7f19280790b8>
files   
{}
self    
<django.contrib.admin.widgets.AdminEmailInputWidget object at 0x7f1928039a58>

我的代码:

models.py:
class AccountManager ( BaseUserManager ) :
    '''  '''
    def _create_user ( self, email, password, is_staff = False, is_superuser = False, **extra_fields ) :
        ''' Creates a User with given email and password '''
        now = timezone.now()
        if not email :
            raise ValueError( 'wrong email' )
        email = self.normalize_email( email )
        user = self.model( email = email, is_staff = is_staff, is_superuser = is_superuser,
                           last_login = now, date_joined = now, **extra_fields )
        user.set_password( password )
        user.save( using = self._db )

        return user


    def create_user ( self, email, password = None, **extra_fields ) :
        '''  '''
        return self._create_user( email, password = None, **extra_fields )


    def create_superuser ( self, email, password, **extra_fields ) :
        '''  '''
        return self._create_user( email, password, is_staff = True, is_superuser = True, is_admin = True, **extra_fields )



class Account ( AbstractBaseUser, PermissionsMixin ) :
    ''' Custom user account inherits from both AbstractBaseUser and PermissionsMixin '''
    email       = models.EmailField( max_length = 255, unique = True, db_index = True, verbose_name = 'email' )
    first_name  = models.CharField( max_length = 255, blank = True, null = True, verbose_name = 'name' )
    last_name = models.CharField( max_length = 255, blank = True, null = True, verbose_name = 'last name' )
    date_joined = models.DateTimeField( default = timezone.now )

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = [ 'first_name' ]

    is_active = models.BooleanField( default = True )
    is_admin  = models.BooleanField( default = False )
    is_staff  = models.BooleanField( default = False )

    objects = AccountManager()


    class Meta :
        '''  '''
        verbose_name = 'user'
        verbose_name_plural = 'users'


    def get_full_name ( self ) :
        '''  '''
        full_name = '{} {}'.format( self.first_name, self.second_name )

        return full_name.strip()


    def get_short_name ( self ) :
        '''  '''
        return self.first_name


    def email_user ( self, subject, message, from_email = None ) :
        '''  '''
        send_mail( subject, message, from_email, [self.email] )


    def __str__ ( self ) :
        '''  '''
        return self.email 


forms.py
User = get_user_model()


class AccountCreationForm ( UserCreationForm ) :
    '''  '''
    def __init__ ( self, *args, **kargs ) :
        super( AccountCreationForm, self ).__init__( *args, **kargs )
        del self.fields[ 'username' ]


    class Meta :
        '''  '''
        model = User
        fields = ( 'email', )



class AccountChangeForm ( UserChangeForm ) :
    '''  '''
    def __init__ ( self, *args, **kargs ) :
        '''  '''
        super( AccountChangeForm, self ).__init__( self, *args, **kargs )
        del self.fields[ 'username' ]


    class Meta :
        '''  '''
        model = User
        fields = ( 'email', )


admin.py
User = get_user_model()

class AccountAdmin ( UserAdmin ) :
    '''  '''
    form = AccountChangeForm
    add_form = AccountCreationForm

    list_display = ( 'email', 'first_name', 'last_name' )
    ordering = ( 'email', )
    list_filter = ( 'is_staff', 'is_active', 'groups' )
    search_fields = ('email', 'first_name', 'last_name' )
    filter_horizontal = ( 'groups', 'user_permissions', )
    ordering = ( 'email', )
    fieldsets = (
        ( None, { 'fields': ( 'email', 'password') } ),
        ( 'Personal info', { 'fields': ( 'first_name', 'last_name' ) } ),
        ( 'Permissions', { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions' ) } ),
        ( 'Important dates', { 'fields': ( 'last_login', 'date_joined' ) } ),
    )
    add_fieldsets = (
        ( None, {
            'classes': ( 'wide', ),
            'fields': ( 'email', 'first_name', 'last_name', 'password1', 'password2' ) }
        ),
    )


admin.site.register( User, AccountAdmin )

完整追溯:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/admin/accounts/account/1/

Django Version: 1.7
Python Version: 3.4.0
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'debug_toolbar',
 'home',
 'accounts')
Installed Middleware:
('debug_toolbar.middleware.DebugToolbarMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')


Traceback:
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  111.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
  567.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  52.         response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
  204.             return view(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/contrib/admin/options.py" in change_view
  1440.         return self.changeform_view(request, object_id, form_url, extra_context)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
  29.             return bound_func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  105.                     response = view_func(request, *args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
  25.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/db/transaction.py" in inner
  394.                 return func(*args, **kwargs)
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/contrib/admin/options.py" in changeform_view
  1428.             errors=helpers.AdminErrorList(form, formsets),
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/contrib/admin/helpers.py" in __init__
  349.             self.extend(list(six.itervalues(form.errors)))
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/forms/forms.py" in errors
  154.             self.full_clean()
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/forms/forms.py" in full_clean
  353.         self._clean_fields()
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/forms/forms.py" in _clean_fields
  362.             value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
File "/home/oleshko/design/.virtualenvs/begemotik/lib/python3.4/site-packages/django/forms/widgets.py" in value_from_datadict
  228.         return data.get(name, None)

Exception Type: AttributeError at /admin/accounts/account/1/
Exception Value: 'AccountForm' object has no attribute 'get'

1 个答案:

答案 0 :(得分:0)

我从文档中拿了一个例子: https://docs.djangoproject.com/en/1.7/topics/auth/customizing/ 它突然开始工作了。 如果所有尝试都没有帮助 - 请参阅说明!!!