django + vue 简单配置登录注册及分页和实例化

时光如瑾雨微凉 2019-10-28

django基本跨域知识点

setting设置

ALLOWED_HOSTS = [‘*‘]??INSTALLED_APPS = [    ‘django.contrib.admin‘,    ‘django.contrib.auth‘,    ‘django.contrib.contenttypes‘,    ‘django.contrib.sessions‘,    ‘django.contrib.messages‘,    ‘django.contrib.staticfiles‘,    ‘app‘,    ‘corsheaders‘,    ‘rest_framework‘,        MIDDLEWARE = [    ‘django.middleware.security.SecurityMiddleware‘,    ‘django.contrib.sessions.middleware.SessionMiddleware‘,    ‘corsheaders.middleware.CorsMiddleware‘,#添加这一行    ‘django.middleware.common.CommonMiddleware‘,    # ‘django.middleware.csrf.CsrfViewMiddleware‘,#注释这一行    ‘django.contrib.auth.middleware.AuthenticationMiddleware‘,    ‘django.contrib.messages.middleware.MessageMiddleware‘,    ‘django.middleware.clickjacking.XFrameOptionsMiddleware‘,]??# 通过ImageField上传文件会自动到达这个文件位置MEDIA_ROOT = os.path.join(BASE_DIR, ‘media‘)??# 允许哪些人可以请求你和请求方式CORS_ORIGIN_ALLOW_ALL = True  #改为true是所有人都可以访问我?

主路由配置URL

导包

from django.contrib import adminfrom django.urls import path,include

配置路由

urlpatterns = [    path(‘admin/‘, admin.site.urls),    path(‘app/‘,include(‘app.urls‘,namespace=‘app‘)),#app为子应用名字]

子路由配置

from django.contrib import adminfrom django.urls import pathfrom . import views??app_name = ‘myapp‘?urlpatterns = [    path(‘index/‘,views.Index.as_view(),name=‘index‘),    path(‘register/‘,views.Register.as_view(),name=‘register‘),    path(‘login/‘,views.Login.as_view(),name=‘login‘),    path(‘details/‘,views.Details.as_view(),name=‘details‘),    path(‘edit/‘,views.Edit.as_view(),name=‘edit‘),    path(‘addgoods/‘,views.Addgood.as_view(),name=‘addgoods‘),?]

admin.py设置

from django.contrib import adminfrom . import models# Register your models here.admin.site.register(models.User)#user为表名admin.site.register(models.Goods)#goods为表名

序列化配置

第一种

在app子应用路径下新建 myserializers.py

内容为:

from rest_framework import serializers?from . import models?class UserSerializers(serializers.ModelSerializer):    class Meta:        models = models.User        fields =  ‘__all__‘??#user,goods为表名?class GoodsSerializers(serializers.ModelSerializer):    class Meta:        model = models.Goods        fields =  ‘__all__‘

第二种

在views.py文件开头加上:

#商品表实例化class Goodsser(serializers.Serializer):#实例化建表字段    id = serializers.IntegerField()    title = serializers.CharField(max_length=30)    price = serializers.DecimalField(max_digits=5,decimal_places=2)    img = serializers.ImageField()    # uid=Userser()??#用户实例化class Userser(serializers.Serializer):    id = serializers.IntegerField(read_only=True)    name = serializers.CharField(max_length=30)    pwd = serializers.IntegerField()    goods_set=Goodsser(many=True)            #正向查找如果反向查找的话在上面用户实例化中添加Goods_set = Goodsser(many=Ture)且两个实例化位置要交换

views.py文件中用到的包

from django.shortcuts import render,redirectfrom django.http import HttpRequest,JsonResponsefrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom rest_framework import serializersfrom django.views import Viewfrom . import models,myserializersimport osimport uuidimport time

vue分页

<template>    <div>?        <nav class="pagination-container">    <ul class="pagination">                <li :class="{‘disabled‘ :p == 1}">            <a @click="add_p(0)">上一页</a>        </li>                <li class="active">            <a href="/courses/?course_type=all&amp;tag=all&amp;fee=all&amp;page=1">1</a>        </li>                     <li :class="{‘disabled‘ :p == total_pag.total_pag}">            <a @click="add_p(1)" >下一页</a>        </li>    </ul></nav>    </div></template>?<script>    export default{        name:‘pag‘,        data(){            return{                p:1,            }        },        mounted(){?        },        methods:{            add_p(type){                if(type){                    if(this.p==this.total_pag.total_pag){                        return;                    }                    this.p += 1                }else{                    if(this.p==1){                        return;                    }                    this.p -= 1                }                // 将当前页码传递给父组件                let data={‘p‘:this.p}                this.$emit(‘change_p‘,data);            },            mul_p(){                if(p == 1){                    return;                }else{                    this.p -= 1                }            },        },        // 接收父组件传过来的变量        props:{            total_pag:{                type:Object,   // object->字典                required:true,  //必须的                            },                    }            }?</script>

diango分页

from django.shortcuts import renderfrom rest_framework.response import Responsefrom rest_framework.views import APIViewfrom rest_framework import serializersfrom django.core.paginator import Paginator,EmptyPage,PageNotAnIntegerfrom . import models??class Index(APIView):    def get(self,request):        page_num = request.query_params.get(‘page_num‘)        # get获取不到默认为None?        if not page_num:            page_num = 1                books = models.Book.objects.all()?        p = Paginator(books, 3)             # ... 3,4 ..5,6 ...         try:            books_data = p.get_page(page_num)        except EmptyPage:            books_data = p.get_page(1)        except PageNotAnInteger:            books_data = p.get_page(1)        ?        book1 = BookSerializer1(instance=books_data,many=True)        book2 = BookSerializer2(instance=books_data,many=True)?        return Response({            ‘data1‘: book1.data,            ‘data2‘: book2.data,            ‘num_pages‘: p.num_pages,            ‘page_range‘: list(p.page_range),        })

diango + vue 登录注册

配置全局axios

import Vue from ‘vue‘import App from ‘./App‘import router from ‘./router‘Vue.config.productionTip = false?import axios from ‘axios‘ //Vue.prototype.axios = axiosVue.prototype.HOME = ‘/app‘//app为主路由??/* eslint-disable no-new */new Vue({  el: ‘#app‘,  router,  components: { App },  template: ‘<App/>‘})

vue取ID刷新窗口

相关推荐

inspuryhq / 0评论 2020-07-28