Django框架——读取数据库数据返回至前端页面

文章目录

  • 前后端不分离
  • 前后端分离

前后端不分离

后端读取数据后,通过模板加载渲染直接返回至前端页面,视图中返回render

urls.py

from django.urls import path, re_path
from . import views


urlpatterns = [
    # 首页路由
    path('', views.IndexView.as_view(), name='index'),
    re_path('index', views.IndexView.as_view()),
]

views.py中读取数据返回至html中

from django.shortcuts import render
from django.views import View
from apps.blogs.models import Blogs


class IndexView(View):

    # 主页面展示
    def get(self, request):
        blogs = Blogs.objects.filter() # 括号内可以写条件
        # blogs = Blogs.objects.all()
        blog_list = []
        for blog in blogs:
            blog_list.append({
                'contents': blog.contents,
                'times': blog.times,
                'province': blog.province,
                'city': blog.city,
                'district': blog.district,
                'address': blog.address,
                'user': blog.user
            })
        context = {
            'blogs': blog_list
        }
        return render(request, 'index.html', context=context)

html页面循环遍历显示后端返回的内容

		<div>
			{% for blog in blogs %}
			<div style="height: 100px;font-size: 20px;">
				需求:{{ blog.contents }}
				<br>
				用户:{{ blog.user }}
				<br>
				时间:{{ blog.times }}
				<br>
				地址:{{ blog.province }} {{ blog.city }} {{ blog.district }} {{ blog.address }}
			div>
			<hr>
			{% endfor %}
		div>

前后端分离

获取页面后,触发js文件中的方法,发起ajax请求,将数据保存到Vue的data数据中,ajax请求的数据返回的是JsonResponse数据,页面通过前端js代码加载渲染

index.js文件

var vm = new Vue({
    el: '#app',
    // 修改Vue变量的读取语法,避免和django模板语法冲突
    delimiters: ['[[', ']]'],
    data: {
        blogs:[]
    },
    mounted(){
        // 获取博客数据
        this.get_blogs();
    },
    methods: {
        // 获取博客数据
        get_blogs(){
            var url = 'http://127.0.0.1:8000/blogs/';
            axios.get(url, {
                responseType: 'json',
            })
                .then(response => {
                    this.blogs = response.data.blogs;
                })
                .catch(error => {
                    console.log(error.response);
                })
        }
    }
});

urls.py

from django.urls import re_path
from . import views


urlpatterns = [
    re_path('index', views.IndexView.as_view(), name='index'),
    re_path('blogs', views.GetblogsView.as_view(), name='blogs'),
]

views.py(注:注意context内部格式,str转化

# 首页显示
class IndexView(View):

    # 主页面展示
    def get(self, request):
        return render(request, 'index.html')


# 读取数据库内容返回至前端页面,vue发起ajax请求到这里
class GetblogsView(View):

    def get(self, request):
        # 获取博客信息
        blogs = Blogs.objects.filter() # 括号内可以写条件
        # blogs = Blogs.objects.all()
        blog_list = []
        for blog in blogs:
            blog_list.append({
                'contents': blog.contents,
                'times': blog.times,
                'province': str(blog.province),
                'city': str(blog.city),
                'district': str(blog.district),
                'address': blog.address,
                'user': str(blog.user),
                'mobile': User.objects.filter(username=blog.user)[0].mobile
            })
        context = {
            'blogs': blog_list
        }
        return http.JsonResponse(context)

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