Django-vue之emement-ui,绑定图片,页面挂载,路由跳转

Posted zhaijihai

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django-vue之emement-ui,绑定图片,页面挂载,路由跳转相关的知识,希望对你有一定的参考价值。

一  emement-ui使用

首先在终端下载安装:npm install element-ui

在vue项目中的main.js下:

import ElementUI from ‘element-ui‘;
import ‘element-ui/lib/theme-chalk/index.css‘;
Vue.use(ElementUI);

二  LuffyCity之建表

from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

from django.contrib.contenttypes.fields import GenericRelation
# Create your models here.

# class CourseType(models.Model):
class Course(models.Model):
    """专题课程"""
    # unique=True 唯一性约束


    name = models.CharField(max_length=128, unique=True)
    course_img = models.CharField(max_length=255)
    brief = models.TextField(verbose_name="课程概述", max_length=2048)

    level_choices = ((0, 初级), (1, 中级), (2, 高级))
    # 默认值为1 ,中级
    level = models.SmallIntegerField(choices=level_choices, default=1)
    pub_date = models.DateField(verbose_name="发布日期", blank=True, null=True)
    period = models.PositiveIntegerField(verbose_name="建议学习周期(days)", default=7)
    # help_text 在admin中显示的帮助信息
    order = models.IntegerField("课程顺序", help_text="从上一个课程数字往后排")

    status_choices = ((0, 上线), (1, 下线), (2, 预上线))
    status = models.SmallIntegerField(choices=status_choices, default=0)
    # 用于GenericForeignKey反向查询,不会生成表字段,切勿删除
    price_policy = GenericRelation("PricePolicy")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "专题课"


class CourseDetail(models.Model):
    """课程详情页内容"""
    course = models.OneToOneField("Course", on_delete=models.CASCADE)
    hours = models.IntegerField("课时")
    # 课程的标语 口号
    course_slogan = models.CharField(max_length=125, blank=True, null=True)
    # video_brief_link = models.CharField(verbose_name=‘课程介绍‘, max_length=255, blank=True, null=True)
    # why_study = models.TextField(verbose_name="为什么学习这门课程")
    # what_to_study_brief = models.TextField(verbose_name="我将学到哪些内容")
    # career_improvement = models.TextField(verbose_name="此项目如何有助于我的职业生涯")
    # prerequisite = models.TextField(verbose_name="课程先修要求", max_length=1024)
    # 推荐课程
    # related_name 基于对象的反向查询,用于替换表名小写_set
    recommend_courses = models.ManyToManyField("Course", related_name="recommend_by", blank=True)
    teachers = models.ManyToManyField("Teacher", verbose_name="课程讲师")

    def __str__(self):
        return "%s" % self.course

    class Meta:
        verbose_name_plural = "课程详细"



class PricePolicy(models.Model):
    """价格与有课程效期表"""
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)  # 关联course or degree_course
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey(content_type, object_id)

    # course = models.ForeignKey("Course")
    valid_period_choices = ((1, 1天), (3, 3天),
                            (7, 1周), (14, 2周),
                            (30, 1个月),
                            (60, 2个月),
                            (90, 3个月),
                            (180, 6个月), (210, 12个月),
                            (540, 18个月), (720, 24个月),
                            )
    valid_period = models.SmallIntegerField(choices=valid_period_choices)
    price = models.FloatField()
    class Meta:
        unique_together = ("content_type", object_id, "valid_period")
        verbose_name_plural = "价格策略"

    def __str__(self):
        return "%s(%s)%s" % (self.content_object, self.get_valid_period_display(), self.price)

class Teacher(models.Model):
    """讲师、导师表"""
    name = models.CharField(max_length=32)
    image = models.CharField(max_length=128)
    brief = models.TextField(max_length=1024)

    def __str__(self):
        return self.name

    class Meta:

        verbose_name_plural = "讲师"

三  vue绑定图片

3.1vue前端页面

<template>
    <div class="course">
        <h1>我是课程</h1>
        <el-row>
            <el-col :span="8" v-for="course in courses">
                <el-card :body-style="{ padding: ‘0px‘ }">
                    <img :src=‘course.course_img.course_img‘ class="image">
                    <div style="padding: 14px;">
                        <span>{{course.name}}</span>
                        <div class="bottom clearfix">
                            <time class="time">{{ currentDate }}</time>
                            <el-button type="text" class="button">
                                <router-link :to="{‘name‘:‘courseDetail‘,‘params‘:{‘id‘:course.id}}">详情</router-link>
                            </el-button>
                        </div>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
    export default {
        data: function () {
            return {
                courses: [],
                currentDate: new Date()
            }
        },
        methods: {
            init: function () {
                let _this = this;
                this.$http.request({
                    url: this.$url + course/,
                    method: get
                }).then(function (response) {
                    console.log(response.data);
                    _this.courses = response.data.data

                })
            }
        },
        mounted: function () {
            this.init()
        }

    }


</script>

<style>
    .time {
        font-size: 13px;
        color: #999;
    }

    .bottom {
        margin-top: 13px;
        line-height: 12px;
    }

    .button {
        padding: 0;
        float: right;
    }

    .image {
        width: 100%;
        display: block;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }

    .clearfix:after {
        clear: both
    }
</style>

3.2后台django代码:

3.2.1序列化

from rest_framework import serializers
from app01 import models


class CourseSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Course
        fields = [id, name, course_img]
    course_img = serializers.SerializerMethodField()
    def get_course_img(self,obj):
        return {course_img:http://127.0.0.1:8000/media/+obj.course_img}


class CourseDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.CourseDetail
        fields = __all__

    course_name = serializers.CharField(source=course.name)
    recommend_courses = serializers.SerializerMethodField()

    def get_recommend_courses(self, obj):
        return [{id: course.pk, name: course.name} for course in obj.recommend_courses.all()]

    teachers = serializers.SerializerMethodField()
    def get_teachers(self, obj):
        return [{id: teacher.pk, name: teacher.name,brief:teacher.brief} for teacher in obj.teachers.all()]

 

3.2.2views

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from app01 import models
from app01.utils.commonUtils import MyResponse
from app01.mySer import CourseSerializer, CourseDetailSerializer
from rest_framework.viewsets import ViewSetMixin

from django.core.exceptions import ObjectDoesNotExist
from django.conf import settings

from rest_framework.pagination import LimitOffsetPagination


# Create your views here.

class Course(ViewSetMixin, APIView):
    def get_course(self, request, *args, **kwargs):

        response = MyResponse()
        course_list = models.Course.objects.all()
        # 加分页器
        page = LimitOffsetPagination()
        page.default_limit=2
        page.max_limit=3
        page_list = page.paginate_queryset(course_list,request,self)


        course_ser = CourseSerializer(instance=page_list, many=True)
        response.msg = 查询成功
        response.data = course_ser.data
        print(response.get_dic)

        return Response(response.get_dic)

    def get_course_detail(self, request, pk, *args, **kwargs):
        response = MyResponse()
        try:
            course_detail = models.CourseDetail.objects.get(course_id=pk)
            course_detail_ser = CourseDetailSerializer(instance=course_detail, many=False)
            response.msg = 查询成功
            response.data = course_detail_ser.data
        except ObjectDoesNotExist as e:
            response.status=101
            response.msg = 您要查询的课程不存在
        except Exception as e:
            response.status=105
            if settings.DEBUG:
                response.msg = str(e)

            else:
                response.msg = 未知错误
        print(response.get_dic)
        return Response(response.get_dic)

 

3.3.3路由

from django.conf.urls import url
from django.contrib import admin

from app01.views import course,img

from django.views.static import serve

from django.conf import settings

urlpatterns = [
    url(r^admin/, admin.site.urls),

    url(r^img/$, img.Img.as_view()),

    url(r^course/$, course.Course.as_view({get:get_course})),
    url(r^course/(?P<pk>d+), course.Course.as_view({get:get_course_detail})),

    url(r^media/(?P<path>.*),serve,{document_root:settings.MEDIA_ROOT}),


]

 

 四  vue页面跳转

<template>
    <div class="courseDetail">
        <h1>我是courseDetail页面</h1>
        <!--{{course_detail}}-->

        <div>
            <h3>{{course_detail.course_name}}</h3>
            <h3>{{course_detail.course_slogan}}</h3>
            <p v-for="teacher in course_detail.teachers"><span>
        {{teacher.name}}:{{teacher.brief}}
      </span>
            </p>
            <h2>推荐课程</h2>
            <p v-for="course in course_detail.recommend_courses"><span>
       <router-link :to="{‘name‘:‘courseDetail‘,‘params‘:{‘id‘:course.id}}">{{course.name}}</router-link>

      </span>
            </p>
        </div>
    </div>

</template>

<script>
    export default {
        data: function () {
            return {
                course_id: this.$route.params.id,
                course_detail: {},
            }
        },
        methods: {
            init: function () {
                let _this = this;
                this.$http.request({
                    url: this.$url + course/ + _this.course_id,
                    method: get
                }).then(function (response) {
                    console.log(response.data);
                    console.log(response.data.data);
                    _this.course_detail = response.data.data

                }).catch(function (response) {
                    console.log(response)
                })
            }
        },
        mounted: function () {
            this.init()
        },
        watch: {
            "$route": function (to, from) {
                console.log(----->to, to);
                console.log(----->from, from);
                this.course_id = to.params.id;
                this.init()
            }
        }

    }


</script>

<style>
    .time {
        font-size: 13px;
        color: #999;
    }

    .bottom {
        margin-top: 13px;
        line-height: 12px;
    }

    .button {
        padding: 0;
        float: right;
    }

    .image {
        width: 100%;
        display: block;
    }

    .clearfix:before,
    .clearfix:after {
        display: table;
        content: "";
    }

    .clearfix:after {
        clear: both
    }
</style>

 

以上是关于Django-vue之emement-ui,绑定图片,页面挂载,路由跳转的主要内容,如果未能解决你的问题,请参考以下文章

django的crsf机制防御详解及在前后端分离中post数据到django-vue

DevExpress之TreeList节点绑定图片

leaflet之唯一值渲染专题图

iOS Sprite Kit教程之xcode安装以及苹果帐号绑定

Android 之 Service(一)启动,绑定服务

立创EDA之3D模型