加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – Django用户创建为自定义用户返回“CustomUserForm”中

发布时间:2020-12-20 13:46:58 所属栏目:Python 来源:网络整理
导读:我为我的 django项目创建了一个自定义用户.当我尝试使用管理员创建新用户时,我无法访问该表单,并收到错误:“KeyUserForm”中未找到“密钥’用户名’” 我的代码如下: models.py from django.core import validatorsfrom django.db import modelsfrom djang
我为我的 django项目创建了一个自定义用户.当我尝试使用管理员创建新用户时,我无法访问该表单,并收到错误:“KeyUserForm”中未找到“密钥’用户名’”

我的代码如下:

models.py

from django.core import validators
from django.db import models
from django.utils import timezone
from django.utils.http import urlquote
from django.utils.translation import ugettext_lazy as _
from django.core.mail import send_mail
from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin

from .managers import CustomUserManager

class CustomUser(AbstractBaseUser,PermissionsMixin):

    email = models.EmailField(_('email address'),max_length=254,unique=True)
    first_name = models.CharField(_('first name'),max_length=30,blank=True)
    last_name = models.CharField(_('last name'),blank=True)
    is_staff = models.BooleanField(_('staff status'),default=False,help_text=_('Designates whether the user can log into this admin '
                    'site.'))
    is_active = models.BooleanField(_('active'),default=True,help_text=_('Designates whether this user should be treated as '
                    'active. Unselect this instead of deleting accounts.'))
    date_joined = models.DateTimeField(_('date joined'),default=timezone.now)

    objects = CustomUserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = []

    class Meta:
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def __unicode__(self):
        return self.email

    def get_absolute_url(self):
        return "/users/%s/" % urlquote(self.email)


    def get_full_name(self):
        """
        Returns the first_name and the last name
        with a space between them.
        """
        full_name = '%s %s' % (self.first_name,self.last_name)
        return full_name.strip()

    def get_short_name(self):
        "Returns a short name for the user."
        return self.first_name

    def email_user(self,subject,message,from_email=None):
        "Sends an email to the user."
        send_mail(subject,from_email,[self.email])

managers.py

from django.contrib.auth.models import BaseUserManager
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

class CustomUserManager(BaseUserManager):

    def _create_user(self,email,password,is_staff,is_superuser,**extra_fields):

        now = timezone.now()

        if not email:
            raise ValueError(_(u'The given username must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email,is_staff=is_staff,is_active=True,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,password=None,**extra_fields):
        return self._create_user(email,False,**extra_fields)

    def create_superuser(self,True,**extra_fields)

forms.py

from django.contrib.auth.forms import UserCreationForm,UserChangeForm
from django.utils.translation import ugettext_lazy as _
from django import forms
from .models import CustomUser

class CustomUserCreationForm(UserCreationForm):
    """
    A form that creats a custom user with no privilages
    form a provided email and password.
    """

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

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

class CustomUserChangeForm(UserChangeForm):
    """
    A form for updating users. Includes all the fields on
    the user,but replaces the password field with admin's
    password hash display field.
    """

    def __init__(self,**kargs):
        super(CustomUserChangeForm,**kargs)
        del self.fields['username']

    class Meta:
        model = CustomUser
        fields = '__all__'

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.translation import ugettext_lazy as _

from .models import CustomUser
from .forms import CustomUserChangeForm,CustomUserCreationForm

class CustomUserAdmin(UserAdmin):

    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_filedsets = (
        (None,{
            'classes': ('wide',),'fields': ('email','password','password2')}
        ),)
    form = CustomUserChangeForm
    add_form = CustomUserCreationForm
    list_display = ('email','first_name','last_name','is_staff')
    search_fields = ('email','last_name')
    ordering = ('email',)

admin.site.register(CustomUser,CustomUserAdmin)

我在代码中找不到任何包含CustomUserForm的文件.有什么关于我的设置是错误的还是我可以看到处理这个问题的东西?

编辑:
这是完整的追溯http://pastebin.com/YcZeM7yD

看来Django正在寻找一个名为(custom_user_model_name)Form的表单,在这个实例中是CustomUserForm.

解决方法

问题是拼写错误add_filedsetss应该是add_fieldsets.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读