Django学习第十五天
前后端分离项目顾名思义,项目的前端和后端是分离的,与之前的django项目不同,前后端分离项目不需要模板不需要静态文件。只需要接收前端发送的请求,以及传递前端需要的数据。
djangorestframework
在前后端分离项目中rest_framework的作用为序列化模型对象为json数据,反序列化json数据为模型对象,以及校验数据是否符合要求,可以通过pip命令在终端中下载模块
pip install djangorestframework
用户注册实例
首先需要一个发送请求的前端页面,当然也可以用postman模拟。由于笔者对于前端的编写比较反感,所以这里使用postman模拟发送请求。设置用户注册请求的路径
user/urls.py
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^register/',views.regiester.as_view()),
]
在view中设置接收post请求的视图
class regiester(GenericAPIView):
def post(self,request):
return JsonResponse({"status_code":200})
构造一个序列化器在app文件夹下新建Serializer文件
class UserSerializer(serializers.ModelSerializer):
password_ok = serializers.CharField(label='确认密码',write_only=True)
phone_string = serializers.CharField(label='短信验证码',write_only=True)
class Meta:
model = User
fields = ('username', 'phone', 'password', 'password_ok', 'phone_string')
def validate(self, data):
username = data['username']
password = data['password']
password_ok = data['password_ok']
phone = data['phone']
phone_string = data['phone_string']
if not re.match(r'^\w{6,12}',username):
raise serializers.ValidationError('用户名长度不符合规则')
try:
user = User.objects.get(username = username)
except:
pass
else:
raise serializers.ValidationError('用户名已存在')
if not re.match(r'^\w{6,18}',password):
raise serializers.ValidationError('密码输入不符合规则')
if password != password_ok:
raise serializers.ValidationError('两次密码输入不一致')
if not re.match(r'1[3,4,5,7,8]\d{9}',phone):
raise serializers.ValidationError('请输入正确的手机号码')
conn = get_redis_connection()
phone_string_right = conn.get(phone)
# if not phone_string_right:
# raise serializers.ValidationError('验证码失效')
if phone_string != '123456':
raise serializers.ValidationError('验证码错误')
return data
随后完善视图类
class regiester(GenericAPIView):
serializer_class = UserSerializer
def post(self,request):
post_data = request.POST
ser = self.get_serializer(data = post_data)
try:
ser.is_valid(raise_exception=True)
except Exception as e:
return JsonResponse({"status_code":400,"err":repr(e)})
# super(UserSerializer,self).create(validated_data)
user = User.objects.create(
username=post_data.get('username'),
password=post_data.get('password'),
phone=post_data.get('phone'),
)
user.set_password(post_data['password'])
user.save()
return JsonResponse({"status_code":200})
模拟发送请求
笔者目前才刚刚开始django的学习,如有错误之处,请大牛见谅指出