博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Django-vue之emement-ui,绑定图片,页面挂载,路由跳转
阅读量:5047 次
发布时间:2019-06-12

本文共 7662 字,大约阅读时间需要 25 分钟。

一  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 modelsfrom django.contrib.contenttypes.models import ContentTypefrom django.contrib.contenttypes.fields import GenericForeignKeyfrom 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前端页面

3.2后台django代码:

3.2.1序列化

from rest_framework import serializersfrom app01 import modelsclass 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 renderfrom rest_framework.views import APIViewfrom rest_framework.response import Responsefrom app01 import modelsfrom app01.utils.commonUtils import MyResponsefrom app01.mySer import CourseSerializer, CourseDetailSerializerfrom rest_framework.viewsets import ViewSetMixinfrom django.core.exceptions import ObjectDoesNotExistfrom django.conf import settingsfrom 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 urlfrom django.contrib import adminfrom app01.views import course,imgfrom django.views.static import servefrom django.conf import settingsurlpatterns = [    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
\d+)', course.Course.as_view({
'get':'get_course_detail'})), url(r'^media/(?P
.*)',serve,{
'document_root':settings.MEDIA_ROOT}),]

 

 四  vue页面跳转

 

转载于:https://www.cnblogs.com/zhaijihai/p/10171008.html

你可能感兴趣的文章
Centos6.4安装JDK
查看>>
201521123069 《Java程序设计》 第4周学习总结
查看>>
线性表的顺序存储——线性表的本质和操作
查看>>
【linux】重置fedora root密码
查看>>
用swing做一个简单的正则验证工具
查看>>
百度坐标(BD-09)、国测局坐标(火星坐标,GCJ-02)和WGS-84坐标互转
查看>>
pig自定义UDF
查看>>
输入名字显示其生日,没有则让输入生日,做记录
查看>>
爬虫综合大作业
查看>>
Kubernetes 运维学习笔记
查看>>
并查集 经典 畅通工程
查看>>
Spark MLlib 之 Naive Bayes
查看>>
php修改SESSION的有效生存时间
查看>>
spring security 11种过滤器介绍
查看>>
Hibernate一对多、多对一关联
查看>>
一、记录Git使用中遇到的问题及解决方法
查看>>
学习网址
查看>>
前端表格插件datatables
查看>>
内部类
查看>>
树链剖分入门
查看>>