Django DRF 登录、注册、分页后端功能实现

DRF框架简介

  • drf是django框架的一个插件,所以要先安装django;
  • 安装命令:pip3 install djangorestframework
  • 使用drf时,要在settings中注册

1、注册功能

– 实例 --在生活中的实例

Django DRF 登录、注册、分页后端功能实现_第1张图片

  • 创建模型 用于注册和登录使用
# 在 model.py 中创建模型(表)  以User为例
from django.db import models

class User(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=128, default=True)

    def __str__(self):     
        return self.username

    class Meta:
        db_table = 'user'
  • 创建序列化器

    在自建 app下创建serializer.py 文件,写序列化工具 使用ModelSerializer

from rest_framework import serializers
from .models import User

class UserModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = '__all__'
  • 功能实现
from django.contrib.auth.hashers import make_password
from rest_framework.views import APIView
from rest_framework.response import Response

from .serializers import UserModelSerializer
from .models import User

class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        if User.objects.filter(username=username):
            return Response({'msg': '该用户已注册!', 'code': 400})
        else:
            if password1 == password2:
                user_data = {'username': username, 'password': make_password(password1)}
                user_serializer = UserModelSerializer(data=user_data)
                if user_serializer.is_valid():
                    user_serializer.save()
                    return Response({'msg': '注册成功!', 'code': 200})
                else:
                    return Response({'msg': user_serializer.errors, 'code': 400})
            else:
                return Response({'msg': '两次密码不一致!', 'code': 400})

完成上面的操作之后,配置路由查看效果!!!

2、登录功能

使用上面的序列化器 和 模型 !!!

Django DRF 登录、注册、分页后端功能实现_第2张图片

  • 功能实现
# 在views.py 中写功能  登录成功后带的参数用于状态保持
from rest_framework.views import APIView
from rest_framework.response import Response

from django.contrib.auth.hashers import check_password

from .models import User

class LoginView(APIView):
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        user = User.objects.filter(username=username).first()
        if user and check_password(password, user.password):
            return Response({'msg': '登录成功', 'code': 200, 'user_id': user.id})
        else:
            return Response({'msg': '登录失败', 'code': 400})

完成上面的操作之后,配置路由查看效果!!!

3、分页功能

  • 创建模型

以新闻为例 可以创建一对多,多对多模型,此处以单标为例!

from django.db import models

class News(models.Model):
    title = models.CharField(max_length=64)
    context = models.TextField()
    stars = models.IntegerField()

    def __str__(self):
        return self.title

    class Meta:
        db_table = 'news'
  • 创建序列化器
class NewsModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = News
        fields = '__all__'
  • 后端代码
from rest_framework.views import APIView
from rest_framework.response import Response

from django.core.paginator import Paginator

from .serializers import NewsModelSerializer
from .models import News


class NewsPage(APIView):
    """分页"""

    def get(self, request):
        # 获取当前页
        current_page = request.query_params.get('current_page')
        # 获取每页显示的数量
        page_size = request.query_params.get('page_size')
        # 获取所有的数据
        news_list = News.objects.all()
        # 实例化分页器
        paginotor = Paginator(news_list, page_size)
        # 获取当前页的数据
        paged = paginotor.page(current_page)
        # 序列化
        news_serializer = NewsModelSerializer(paged, many=True)
        # 返回数据
        return Response({
            'data': news_serializer.data,
            'page_list': [i for i in paginotor.page_range],
            'page_sum': paginotor.num_pages

接口地址:http://127.0.0.1:8000/app01/news/

请求方法:GET

请求参数:current_page(当前页) page_size(每页展示几条数据)

  • 前端代码 vue 工具:WebStorm
<template>
  <div>
    <h3 class="t1">新闻展示页面h3>
    <hr class="t1">
    <table class="t1">
      <tr>
        <td>新闻编号td>
        <td>新闻标题td>
        <td>新闻内容td>
        <td>新闻点赞td>
      tr>
      <tr v-for="item in news_list">
        <td>{{item.id}}td>
        <td>
          
          <router-link :to="{name:'NewsDetail',query:{'news_id':item.id}}">{{item.title}}router-link>
        td>
        <td>{{item.context}}td>
        <td>{{item.stars + '人'}}td>
      tr>
      <tr>
        <td colspan="5" class="td1">td>
      tr>
      <tr>
        <td colspan="5">
          <button @click="upPage">上一页button>
          <button v-for="item in page_list" @click="jump(item)">{{item}}button>
          <button @click="downPage">下一页button>
        td>
      tr>
    table>
  div>
template>

<script>
  import axios from 'axios'

  export default {
    data() {
      return {
        current_page: 1,
        page_size: 2,
        news_list: [],
        page_list: []
      }
    },
    methods: {
      // 上一页
      upPage() {
        if (this.current_page > 1) {
          this.current_page--
          this.getnews()
        }
      },
      // 下一页
      downPage() {
        if (this.current_page < this.page_list.length) {
          this.current_page++
          this.getnews()
        }
      },
      // 点击跳转
      jump(page) {
        this.current_page = page
        this.getnews()
      },
      getnews() {
        this.axios({
          url: 'app01/newspage/',
          params: {'current_page': this.current_page, 'page_size': this.page_size}
        }).then(res => {
          this.news_list = res.data.data
          console.log(this.news_list)
          this.page_list = res.data.page_list
        })
      }
    },
    created() {
      this.getnews()
    }
  }
script>

<style scoped>
  .t1 {
    margin: 15px auto;
    width: 80%;
    text-align: center;
  }

  .td1 {
    height: 40px;
  }

style>

  • 前端点击跳转详情页
<router-link :to="{name:'NewsDetail',query:{'news_id':item.id}}">
<-- 跳转至详情页之后,获取路由中的参数 --!>
news_id = this.$route.query.news_id 

使用axios 请求后端的数据(详情数据)

  • 后端功能
from rest_framework.views import APIView
from rest_framework.response import Response

from .serializers import NewsModelSerializer
from .models import News
	
class NewsView(APIView):
   """获取详情页面"""
    def get(self, request):
        news_id = request.query_params.get('news_id')
        news_obj = News.objects.filter(pk=news_id)
        news_serializer = NewsModelSerializer(news_obj, many=True)
        return Response(news_serializer.data)

4、删除功能

5、修改功能

6、前端状态保持

京东\淘宝

用户名+密码 先登录 + token user_id

<-- 传入需要保持的数据 --!>
localStorage.setItem('user_id', res.data.user_id) 

4、删除功能

5、修改功能

6、前端状态保持

京东、淘宝等网站都需要!!!

用户名+密码 先登录 + token user_id

<-- 传入需要保持的数据 --!>
localStorage.setItem('user_id', res.data.user_id) 
关注我 明天完善删除和修改功能!!!感谢支持,留下一间三连呗 么么哒~

你可能感兴趣的:(Django,python,django,python,vue)