如何解决引发的错误:没有名为'django.contrib.customuser'的模块

时间:2016-07-01 16:36:33

标签: django django-custom-user django-custom-manager

我是Django的新手,试图为我的项目创建一个自定义用户。当我运行服务器时,它会引发没有名为'django.contrib.customuser'的模块,有时,Manager不可用; auth.User已被替换为Mysite.CustomUser。甚至我改变了我的设置:django.contrib.auth到django.contrib.custommuser。请有人帮我解决这个问题。这是我的代码

models.py:

from datetime import datetime
from django.db import models
from django.contrib.auth.models import User, BaseUserManager, AbstractUser,   AbstractBaseUser

from django.utils.translation import ugettext_lazy as _

class CustomUserManager(BaseUserManager):

    def _create_user(self, username, email, u, password, is_staff, is_active, **extra_fields):
        now = datetime.now()
        if not email:
            raise ValueError('Users must have an email address')
        email = self.normalize_email(email)
        user = self.model(username=username, email=email, u=u, password=password,
             is_staff=is_staff, is_active=False, last_login=now, date_joined=now, **extra_fields)

        user.set_password(password)
        user.save(using=self._db)
        return user

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

    def create_superuser(self, username, email, u, password = None):
        user = self._create_user(username, email, u, password, True, True)

        user.set_password(password)
        user.is_active=True
        user.is_admin = True

        user.is_superuser = True
        user.save(using=self._db) 
        return user



class CustomUser(AbstractBaseUser):
    username = models.CharField(max_length=30)
    email = models.EmailField(max_length=30, unique=True, db_index=True)
    password1 = models.CharField(max_length=30)
    password2 = models.CharField(max_length=30)
    CHOICES= (('LinkedinUser', 'LinkedinUser'),('FacebookUser', 'FacebookUser'),)
    u = models.CharField(choices=CHOICES, max_length=20, default=0)
    date_joined  = models.DateTimeField(_('date joined'), default=datetime.now)
    is_active    = models.BooleanField(default=True)
    is_admin     = models.BooleanField(default=False)
    is_staff     = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    REQUIRED_FIELDS = ('username', 'u')
    USERNAME_FIELD = 'email'
    objects = CustomUserManager()

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

    def get_full_name(self):
        # The user is identified by their email address
        return self.email

    def get_short_name(self):
        # The user is identified by their email address
        return self.email

    def __str__(self):              # __unicode__ on Python 2
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return True

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        return self.is_admin

forms.py

from django import forms
from django.contrib.auth.forms import UserChangeForm, UserCreationForm

from .models import CustomUser#, LinkedInUser, FacebookUser
import re
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth import get_user_model


class CustomUserForm(forms.ModelForm):

    username = forms.RegexField(regex=r'^\w+$', widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("username"), error_messages={ 'invalid': _("This value must contain only letters, numbers and underscores.") })
    email = forms.EmailField(widget=forms.TextInput(attrs=dict(required=True, max_length=30)), label=_("Email address"))
    password1 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password"))
    password2 = forms.CharField(widget=forms.PasswordInput(attrs=dict(required=True, max_length=30, render_value=False)), label=_("Password (again)"))
    CHOICES= (('LinkedinUser', 'LinkedinUser'),('FacebookUser', 'FacebookUser'),)
    u = forms.ChoiceField(choices=CHOICES, label='ID', widget=forms.RadioSelect()) 

    class Meta :
        model = CustomUser
        fields = [ 'username', 'email', 'password1', 'password2', 'u' ]

        User = get_user_model()

    def clean_name(self):
        try:
            user = User.objects.get(username__iexact=self.cleaned_data['username'])
        except User.DoesNotExist:
            return self.cleaned_data['username']
        raise forms.ValidationError(_("The username already exists. Please try another one."))

    def clean(self):
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise forms.ValidationError(_("The two password fields did not match."))
        return self.cleaned_data


class CustomUserCreationForm(UserCreationForm):
    """
    A form that creates a user, with no privileges, from the given email and
    password.
    """

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

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

admin.py

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

from .models import CustomUser
from .forms import CustomUserCreationForm

class CustomUserAdmin(admin.ModelAdmin):
    form = CustomUserCreationForm

admin.site.register(CustomUser, CustomUserAdmin)

backends.py:

from models import CustomUser

class CustomUserAuth(object):

    def authenticate(self, username=None, password=None):
        try:
            user = CustomUser.objects.get(email=username)
            if user.check_password(password):
                return user
        except CustomUser.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            user = CustomUser.objects.get(pk=user_id)
            if user.is_active:
                return user
            return None
        except CustomUser.DoesNotExist:
            return None

1 个答案:

答案 0 :(得分:0)

django.contrib.customuser移除django.contrib.authINSTALLED_APPScustomuser包下没有django.contrib个应用程序,auth可以省略(以避免潜在的名称更改)。

此外,我建议你重新阅读the Django docs on auth customization。大多数更改都是可选的,您的代码应该通过重用基类来简化,除非您的方法有所不同。 文档还提到,要交换用户模型,您需要将设置更新为AUTH_USER_MODEL = 'customuser.CustomUser'