First, the functional requirements analysis
1、banner
2, the recommended list of articles
3, article tab navigation
4, the list of articles
5, Page
Second, the model design
According to functional analysis, we need the following table, a lot of accumulated experience and capabilities
1, table and field analysis
a classification Articles
b article table
c article comments table
d recommend the article table
e carousel Chart
2, model definition
Define a base class model, extracting common field
Created, Updated, tombstone
Analysis of a function of each table, according to the coding model field
Third, the paper label navigation
1. Interface Design
Category Description
GET request method
url /
Parameters None Parameter
2. Return results
Back to News page, direct rendering the template
#insert news tag data
INSERT INTO tb_tag(name, create_time, update_time, is_delete) values
( 'Python base', now (), now (), 0),
( 'Python senior', now (), now (), 0),
( 'Python function', now (), now (), 0),
('PythonGUI', now(), now(), 0),
( 'Linux tutorials', now (), now (), 0),
( 'Python framework', now (), now (), 0);
Fourth, the news list function
1, business process analysis
Determining whether a transfer label classification ID distal empty, whether the integer range exceeds
Analyzing this article the front end b of pages transmitted is empty, whether the integer range exceeds
2, interface design
Category Description
GET request method
url /news/
Parameter Description:
You must describe whether parameters type
No integer ID tag label classification
Integer is the current page article pages
3, returns the result:
json
{
"errno": "0",
"errmsg": "",
"data": {
"total_pages": 61,
"news": [
{
"Digest": "or the python with from ... import or import from ... import ... ... AS corresponding to import module, and a similar effect with the use of C language header files include actually introduced. ... "
"Title": "import module Detailed method for introducing"
"author": "python",
"image_url": "/media/jichujiaochen.jpeg",
"Tag_name": "Python Foundation",
"update_time": "2018年12月17日 14:48"
},
{
"Digest": "If you turned out to be a php programmer, php function very familiar to you (PS: the original is a webmaster php programmer), but now because of work or other reasons to learn python, but p ..." ,
"Title": "to once phper programmers recommend learning site"
"author": "python",
"image_url": "/media/jichujiaochen.jpeg",
"Tag_name": "Python Foundation",
"update_time": "2018年12月17日 14:48"
}
]
}
}
mysql -u root -p -D tzpj <tb_news_20181217.sql. into the database
news / modile.py Code
django.db Import Models from
from utils.models Import BaseModel
class Tag (BaseModel):
"" "
Article Category label model
" ""
# field
name = models.CharField ( 'label name', max_length = 64, help_text = ' tag name ')
class Meta:
ordering = [' -update_time ',' -id '] # sort
db_table = "tb_tag" # specify the database table name
verbose_name =' Posts Tagged '# the point name in the admin site
verbose_name_plural = verbose_name # display point plural name
DEF __str __ (Self):
return self.name
class News (BaseModel):
"" "
Base model
" ""
title = models.As CharField ( 'title', max_length = 150, help_text = 'title')
digest = models.CharField ( 'Summary', max_length = 200, help_text = ' Summary')
Content = models.TextField ( 'content', help_text = 'content')
Clicks = models.IntegerField ( 'hits', default = 0 , help_text = 'hits')
image_url = models.URLField ( 'picture url', default = '', help_text = ' picture url')
Tag = models.ForeignKey ( 'Tag', on_delete = models.SET_NULL, null = True )
author = models.ForeignKey ( 'user.user', on_delete = models.SET_NULL, null = True)
class Meta -:
ordering = [ '-update_time', '-id'] # sort
db_table = "tb_news" # specified database table name
verbose_name = 'news'# Displayed in the admin site point name
verbose_name_plural = verbose_name #-point complex display name
def __str __ (self):
self.title return
class Comments (BaseModel):
"" "
Comment model
" ""
Content = models.TextField ( 'content', help_text = 'content')
author = models.ForeignKey ( 'user.user', on_delete = Models. SET_NULL, null = True)
News models.ForeignKey = ( 'News', on_delete = models.CASCADE)
class Meta -:
ordering = [ '-update_time', '-id'] # sort
db_table = "tb_comments" # specified database table
verbose_name = 'comments' # display in admin site point name
verbose_name_plural = verbose_name # plurality of display dots name
DEF __str __ (Self):
return '<comment {}>' format (self. .the above mentioned id)
class HotNews (BaseModel):
"" "
Recommended Reading Model
"" "
News = models.OneToOneField ( 'News', on_delete = models.CASCADE)
priority = models.IntegerField (' priority ', help_text =' priority ')
class Meta -:
Ordering = [' -update_time ',' - ID '] # sort
db_table = "tb_hotnews" # specified database table
verbose_name =' Popular article '# display in admin site point name
verbose_name_plural = verbose_name # display point complex name
DEF __str __ (Self):
return' <Top article {} > 'the format (self.id).
class Banner (BaseModel):
"" "
carousel FIG
" ""
image_url = models.URLField (' FIG rotation ', help_text =' carousel FIG url ')
Priority = models.IntegerField ( 'priority', help_text = 'priority')
= models.OneToOneField News ( 'News', on_delete = models.CASCADE)
class Meta -:
Ordering = [ 'priority', '-update_time', '-id'] # sort
db_table = "tb_banner" # specified database table
verbose_name = 'Popular article' site admin # shown in point name
verbose_name_plural = verbose_name # plurality of display dots name
DEF __str __ (Self):
. return '<FIG rotation} {>' the format (self.id)
News / codes the views.py
import logging
from django.shortcuts import render
from django.views import View
from django.db.models import F
from django.core.paginator import Paginator
from .models import Tag, News
from . import constants
from utils.res_code import json_response
logger = logging.getLogger('django')
def index(request):
"""
新闻首页视图 only默认带ID
url: /
:param request:
:return:
"""
# 新闻标签
tags = Tag.objects.only('name').filter(is_delete=False)
return render(request, 'news/index.html', context={
'tags': tags
})
class NewsListView(View):
"""
News list view
"" "
DEF GET (Self, Request):
#. 1, acquisition parameters
the try:
tag_id = int (request.GET.get ( 'Tag', 0))
the except Exception AS E:
logger.error ( 'Error tab , \ n {} 'the format (E)).
tag_id = 0
the try:
tag_id = int (request.GET.get (' tag ', 0))
the except Exception AS E:
logger.error (' tag error, \ n { } '. the format (E))
tag_id. 1 =
# 2, the query set values acquired return dictionary
news_queryset = News.objects.values (' ID ',' title ',' Digest ',' image_url ',' UPDATE_TIME ',
' tag__name ',' author__username '). annotate (tag_name = F ('tag_name'),author=F('author__username'))
#过滤
IF tag_id #:
# = news_queryset.filter News (is_dalete = False, tag_id = tag_id)
# the else:
# = news_queryset.filter News (is_dalete = False)
News = news_queryset.filter (is_dalete = False, tag_id = tag_id) or news_queryset. filter (is_dalete = False)
#. 3, paging
the paginator = Paginator (News, constants.PER_PAGE_NEWS_COUNT)
# acquires this page fault tolerant data get_page
news_info = paginator.get_page (page)
#. 4, return data
data = {
'total_pages': the paginator. NUM_PAGES,
'News': List (news_info)
}
return json_response (Data = Data)
is serialized: the particular memory object can be converted to a string stored
utils / res_code.py Code
import datetime
from django.http import JsonResponse
from django.core.serializers.json import DjangoJSONEncoder
class MyJSONEncoder(DjangoJSONEncoder):
default DEF (Self, O):
IF the isinstance (O, A datetime.datetime):
return o.astimezone () the strftime. ( '% Y-M-% D%% H:% M:% S') is converted to local # time
the else:
. Super return () default (O)
def json_response(errno=Code.OK, errmsg='', data=None, kwargs=None):
json_dict = {
'errno': errno,
'errmsg': errmsg,
'data': data
}
if kwargs and isinstance(kwargs, dict):
json_dict.update(kwargs)
return JsonResponse(json_dict, encoder=MyJSONEncoder)
V. Recommended News
1, interface design
Category Description
GET request method
url /
Parameters None Parameter
2, returns the result
Back to News page, direct rendering the template
news / vies.py Code
index DEF (Request):
"" "
News view
url: /
" ""
# News Tags
. Tags = Tag.objects.only ( 'name') filter (is_delete = False)
# Top News objects.select_related ( 'news' ) more than one time to get data from the database
hot_news = HotNews.objects.select_related('news').only('news__title', 'news__image_url', 'news_id').filter(is_delete=False).order_by('priority', '-news__clicks')[:constants.SHOW_HOTNEWS_COUNT]
return render(request, 'news/index.html', context={
'tags': tags,
'hot_news': hot_news
})
Six, carousel FIG functional
interface design
1, interface description:
Category Description
request method the GET
URL defined / news / banners /
parameter format no parameter
2, returns the result: JSON #
{
'erron': '0',
'ErrMsg': 'OK'
'Data': {
'Banners': [
{
'image_url': '/ Media / jichujiaochen.jpeg',
'news_id': 221,
'news_title': 'quick sort algorithm Python'
},
{
'image_url': '/ Media / python_advanced.jpeg',
'news_id': 707,
'news_title': 'Python sequence mapped unpacked operations'
}
]
}
}