Rest Framework 实现登录注册

Rest Framework 实现登录注册

Django中提供了一个AbstractUser类,我们可以用来自由的定制我们需要的model

它里面有写好的username,password 等字段,如果有需要我们可以重写,一般直接复用就好

from django.contrib.auth.models import AbstractUser
		class User(AbstractUser):
		
		    tel=models.CharField(max_length=11)
		    class Meta:
		        db_table='user'

继承AbstractUser需要在sttings里配置:

	AUTH_USER_MODEL='demo.User'

进行序列化serializers

from django.contrib.auth.hashers import make_password, check_password
from rest_framework import serializers
	#注册
class RegSerializers(serializers.ModelSerializer):
    pwd2=serializers.CharField(max_length=256,min_length=4,write_only=True)
    tel=serializers.CharField(max_length=11,min_length=11)
    class Meta:
        model=User
        fields=('username','password','pwd2','tel')
    def validate(self, attrs):
        if attrs['pwd2']!=attrs['password']:
            raise ValidationError('两次密码输入不一致')
        del attrs['pwd2']
 		#对密码进行加密 make_password
        attrs['password'] = make_password(attrs['password'])
        return attrs
    #登录
class LogSerializers(serializers.ModelSerializer):
    username=serializers.CharField(max_length=6)
    class Meta:
        model=User
        fields=('username','password')
    def validate(self, attrs):
        user_obj=User.objects.filter(username=attrs['username']).first()
        if user_obj:
        #check_password 可以将加密后的密码与输入的密码进行对比
            if check_password(attrs['password'],user_obj.password):
                return attrs
        raise ValidationError('用户名或密码错误')

我们还可以添加Token 或者是手机验证码来让账号更安全

在views.py里:

from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import *
class RegList(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = RegSerializers
    def create(self, request, *args, **kwargs):
        res=RegSerializers(data=request.data)
        if res.is_valid():
            res.save()
             #res.errors 定义好的错误信息
        return Response(res.errors)

class LogList(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = LogSerializers
    def create(self, request, *args, **kwargs):
        data=request.data
        res=LogSerializers(data=data)
        if res.is_valid():
            return Response(res.validated_data)
            #res.errors 定义好的错误信息
        return Response(res.errors)

我们继承 ModelViewSet

URL

	from django.conf.urls import url, include
	from django.contrib import admin
	from .views import *
	from rest_framework.documentation import include_docs_urls
	from rest_framework.routers import DefaultRouter
	router=DefaultRouter()
	router.register('reg',RegList,'reg')
	router.register('log',LogList,'log')
	urlpatterns = [
	    url(r'', include(router.urls)),
	    #创建API文档
	    url(r'^api/', include_docs_urls(title='haha')),
	]

你可能感兴趣的:(Rest,Framework)