现在做前台数据展现,首先在views.py内写一个处理函数:
from django.shortcuts import render, HttpResponse
from web_app.models import *
def news_content(request):
# http://127.0.0.1:8000/news/?id=1
id_num = request.GET.get('id')
context = {}
try:
context['News'] = News.objects.get(id=id_num)
context['title'] = context['News'].title
except News.DoesNotExist:
context['News'] = '404'
context['title'] = '404'
return render(request, 'web_app/article.html', context)
return render(request, 'web_app/article.html', context)
根据url内id参数查询新闻内容,然后返回一个模板文件与dict对象;接着在templates路径下创建我们的html模板文件:
(这里我用Bootstrap可视化布局系统简单演示一下)
{% include "web_app/head.html" %}
{{News.title}}
{% autoescape off %}
{{News.content}}
{% endautoescape %}
{% include "web_app/foot.html" %}
head.html:
{{title}}
这是一个新闻内容展示页,涉及到了简单的django模板语法,include标签调用页面公用部分(网站的头部和底部),由于从数据库查询出来的文章内容是字符串,需要用{% autoescape off %}{% endautoescape %}标签进行html转义。
最后在url.py中加上路由:
from django.urls import path, re_path
from web_app import views
from web_app import upload as u
urlpatterns = [
re_path(r'^$', views.index),
re_path(r'^news/$', views.news_content),
re_path(r'^upload_file/$', u.upload, name='upload'),
]
打开web服务,查看效果:
还有更多的django模板语法就不详细说了,不过我个人还是喜欢前端与后端分离的模式,后台直接返回json数据就行了;要实现这种api,先安装一个基于Django的框架,rest_framework。
app文件夹内新建一个serializers.py文件:
from rest_framework import serializers
from web_app.models import *
class NewsSerializer(serializers.ModelSerializer):
class Meta:
model = News
fields = ('id', 'title', 'news_class', 'date', 'show', 'content')
views.py内写一个返回json格式数据的类:
from web_app.models import *
from web_app.serializers import *
from rest_framework.views import APIView
from django.http import JsonResponse
class GetNews(APIView):
# http://127.0.0.1:8000/get_news/?id=1
def get(self, request):
# 获取url参数
id_num = request.GET.get('id')
serializer = NewsSerializer(News.objects.all(), many=True)
# 返回信息
msg = {
'success': True,
'data': serializer.data
}
# 防止中文乱码
return JsonResponse(msg, json_dumps_params={'ensure_ascii': False})
别忘了url.py:
from django.urls import path, re_path
from web_app import views
from web_app import upload as u
# app url 配置
urlpatterns = [
re_path(r'^$', views.index),
re_path(r'^news/$', views.news),
re_path(r'^upload_file/$', u.upload, name='upload'),
re_path(r'^get_news/$', views.GetNews.as_view()),
]
测试返回json:
Django这个框架暂时先玩到这里,如果需要开发一个正式的项目还需更深入的学习。