博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django rest framework 自定义用户以及自定义认证方式
阅读量:6824 次
发布时间:2019-06-26

本文共 4819 字,大约阅读时间需要 16 分钟。

自定义一个用户很简单models.py

from django.db import modelsfrom django.contrib.auth.models import (    BaseUserManager, AbstractBaseUser)class MyUserManager(BaseUserManager):    def create_user(self, email, date_of_birth, password=None):        """        Creates and saves a User with the given email, date of        birth and password.        """        if not email:            raise ValueError('Users must have an email address')        user = self.model(            email=self.normalize_email(email),            date_of_birth=date_of_birth,        )        user.set_password(password)        user.save(using=self._db)        return user    def create_superuser(self, email, date_of_birth, password):        """        Creates and saves a superuser with the given email, date of        birth and password.        """        user = self.create_user(            email,            password=password,            date_of_birth=date_of_birth,        )        user.is_admin = True        user.save(using=self._db)        return user               class MyUser(AbstractBaseUser):    email = models.EmailField(        verbose_name='email address',        max_length=255,        unique=True,    )    date_of_birth = models.DateField()    is_active = models.BooleanField(default=True)    is_admin = models.BooleanField(default=False)    objects = MyUserManager()    USERNAME_FIELD = 'email'    REQUIRED_FIELDS = ['date_of_birth']    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):        "Is the user a member of staff?"        # Simplest possible answer: All admins are staff        return self.is_admin

然后是admin.py

class UserAdmin(BaseUserAdmin):    # 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', 'date_of_birth', 'is_admin')    list_filter = ('is_admin',)    fieldsets = (        (None, {'fields': ('email', 'password')}),        ('Personal info', {'fields': ('date_of_birth',)}),        ('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', 'date_of_birth', 'password1', 'password2')}        ),    )    search_fields = ('email',)    ordering = ('email',)    filter_horizontal = ()# Now register the new UserAdmin...admin.site.register(MyUser, UserAdmin)# ... and, since we're not using Django's built-in permissions,# unregister the Group model from admin.admin.site.unregister(Group)

最后是settings.py

AUTH_USER_MODEL = 'customauth.MyUser'AUTHENTICATION_BACKENDS = (    'accounts.backends.LoginBackend',)

这样一个自定义的用户模型就弄好了,接下来是自定义登录字段

class LoginBackend(object):    def authenticate(self, username=None, password=None):        if username:            #email            if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", username) != None:                try:                    user = User.objects.get(email=username)                    if user.check_password(password):                        return user                except User.DoesNotExist:                    return None            #mobile            elif len(username)==11 and re.match("^(1[3458]\d{9})$", username) != None:                try:                    user = User.objects.get(mobile=username)                    if user.check_password(password):                        return user                except User.DoesNotExist:                    return None              #nick            else:                try:                    user = User.objects.get(username=username)                    if user.check_password(password):                        return user                except User.DoesNotExist:                    return None                        else:            return None    def get_user(self, user_id):        try:            return User.objects.get(pk=user_id)        except User.DoesNotExist:            return None

转载地址:http://fwgzl.baihongyu.com/

你可能感兴趣的文章
VS2010使用Qt库
查看>>
Python特殊语法--filter、map、reduce、lambda
查看>>
[原] Jenkins Android 自动打包配置(转)
查看>>
[Redux] Passing the Store Down with <Provider> from React Redux
查看>>
javascript笔记7-事件
查看>>
大数据处理分析的六大最好工具
查看>>
【转】俞军给淘宝产品经理的分享
查看>>
Thrift使用实例
查看>>
Nand flash uboot 命令详解【转】
查看>>
曲线的奇点
查看>>
【Linux】了解服务器的情况
查看>>
解决Spring配置文件不显示design和source, namespace 问题
查看>>
Efficiently traversing InnoDB B+Trees with the page directory--slot
查看>>
算法笔记_191:历届试题 大臣的旅费(Java)
查看>>
乐为物联网平台初步体验(1)
查看>>
利用ArcGIS水文分析工具提取河网
查看>>
看58同城9月招聘季 大数据显示蓝领薪酬更高
查看>>
跳台阶
查看>>
Android API学习 SoundPool 和 MediaPlayer
查看>>
郁闷的一天
查看>>