Django front-end and back-end separate development-news management system

Project source download:

Front-end System Architecture Diagram

I. Creating Front-end Projects and Applications startproject newsapi
python startapp article

Copy the static and templates folders into our project.
And in the setting APP, add article


Add configuration static file in setting

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static').replace('', '/')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

The working principle of the web front-end is that the url corresponding to the request back-end is parsed, passed to the html template, and returned to the browser (user).

1. Basic method - urlopen

urllib.request.urlopen(url,data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)

  • url: The Web Site to Open
  • data: data submitted by Post
  • Timeout: Set the site access timeout
    urlopen () of urllib.request module is used to get pages directly. The data format of pages is bytes type. Decode () is needed to decode and convert to str type.
    from urllib import request
    response = request.urlopen(r'') <http.client.HTTPResponse object at 0x00000048BC908> HTTPResponse type
    page =
    page = page.decode('utf-8')
    The urlopen return object provides methods:
  • Read (), readLine (), readlines (), fileno (), close (): Operating on HTTPResponse type data
  • info(): Returns the HTTPMessage object, representing the header information returned by the remote server
  • getcode(): Returns the Http status code. If it is an HTTP request, the 200 request is successfully completed; 404 web site is not found
  • geturl(): Returns the url of the request
2. Use Request

urllib.request.Request(url,data=None, headers={}, method=None)
The request () is used to wrap the request, and the page is retrieved through urlopen ().
url = r''
headers = {
'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
'Referer': r'',
'Connection': 'keep-alive' }
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
Data used to wrap head:

  • User-Agent: This header can carry the following information: browser name and version number, operating system name and version number, default language
  • Referer: It can be used to prevent chain theft. Some website pictures show the source http:/***.com, which is identified by checking Referer.
  • Connection: Represents the connection status and records the status of the Session.

1. Import package

from urllib import request, parse

    import json
except ImportError:
    import simplejson as json
from django.shortcuts import render
from urllib.parse import urljoin

# Create your views here.


2. Introduce all API s

category_url = ''
articles_url = ''
hotarticles_url = ''
ad_url = ''
items_url = ''

3. Define a common access parsing API method

# Read api data
def getdata(url, data=None):
    # url = r'http://xxx/xxx/xxxx?'
    headers = {
        'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                  r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
        'Referer': r'',
        'Connection': 'keep-alive',
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
    # data = {
    #     'first': 'true',
    #     'pn': 1,
    #     'kd': 'Python'
    #     }
    # The main function of urlencode () is to attach the url to the data to be submitted.
    # After urlencode () conversion, the data data data is? first=true?pn=1?kd=Python, and the final submitted url is? first=true?pn=1?kd=Python
    # http://xxxxx/xx/xx?first=true?pn=1?kd=Python
        if data:
            # data = parse.urlencode(data).encode('utf8')
            # If the data parameter must be passed bytes (byte stream) type, if it is a dictionary, it can be coded with urllib.parse.urlencode().
            # data = bytes(parse.urlencode(data), encoding="utf8")
            data = '?' + parse.urlencode(data)
            # The request () is used to wrap the request, and the page is retrieved through urlopen ().
            url = urljoin(url, data)
            req = request.Request(url=url, headers=headers, method='GET')
            req = request.Request(url=url, headers=headers)

        reponsedata = request.urlopen(req, timeout=10).read()
        reponsedata = reponsedata.decode('utf-8')
        returndata = json.loads(reponsedata)
    except Exception as e:
        returndata = {'result': e, 'code': e, 'msg': 'request api Data error!', 'data': '{}', 'redirect_url': ''}
    return returndata

4. News classification, hot news and advertisement are defined as global variables, and getdata functions are called respectively.

# Implementing global variables
def globl_init(request):
    # Categorizing News
    # #category_list = Category.objects.all()
    category_list = getdata(category_url)
    # Get Hot News
    # hot_articles = Article.objects.filter(is_active=True)[0:5]
    hot_articles = getdata(hotarticles_url)
    # Take Advertising Data
    ad_list = getdata(ad_url)
    user = request.user
    return locals()

Global variables must be configured in setting s if they are to take effect on each page.

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'artcile.views.globl_init', # Newly added

5. Realizing Home Page Function

def index(request):
    data = {
        "ordering": '-id',
    article_data = getdata(articles_url, data)
    article_list = article_data["results"]

    user = []
    return render(request, 'index.html', locals())
# Article Details Page
def article(request):

# search
def search(request):

# Classification page
def category(request):
locals: No need to encapsulate the result (article_list) into context, and local() automatically takes the result as context data and renders it into a template

6. Template file index.html

index.html inherits and underlying base.html file, which includes column navigation, content section (including left-hand broadcast, left-hand news list, right-hand advertisement, right-hand hot news, right-hand advertisement, right-hand attention to us), footer section.

{% load staticfiles %}
{% load dictfilter %}
<!doctype html>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<meta name="keywords" content="" />
<meta name="description" content="" />
<link href="{% static 'css/base.css' %}" rel="stylesheet">
{% block custom_css %}{% endblock %}
<script type="text/javascript" src="{% static 'js/jquery-1.11.1.min.js' %}"></script>
<script type="text/javascript" src="{% static 'js/slide.js' %}"></script>
<script type="text/javascript" src="{% static 'js/jquery.cookie.js' %}"></script>
{% block custom_js %}{% endblock %}

  <!--Column navigation-->
<div class="header">
    <div class="layout logo">
        <a href="" class="logoimg"><img src="/static/images/careeru.png" class="logoimg"></a>
        <ul class="nav">
            <li class="cur"><a href="/">home page</a></li>
           {% for category in category_list %}
                {% if category|key:"id" == categoryid %}
                   <li class="columnnav  cur">
                {% else %}
                   <li class="columnnav">
                {% endif %}
                     <a href="{% url 'category' %}?cid={{category|key:"id" }}">{{category|key:"title" }}</a>

           {% endfor %}

        <div  class="userlogin">
           <div  id="logined" style="display: none">
             <span id="navlogout"><a href="javascript:void(0)">Cancellation</a></span>
             <span id="navprofile"></span>
          <div  id="nologin">
              <span id="navregister"><a class="curegister" href="javascript:;">register</a></span>
              <span id="navlogin"><a class="ulogin" href="javascript:;" data-status="nologin">Sign in</a>    </span>
        <form  action="{% url 'search' %}" id="Search" name="search_box" method="get" target="_blank" >
            <input id="searchKey" title="Please enter keywords" name="query"  autocomplete="off"  type="text">
            <input id="searchBtn" value=""  onclick="" aria-pressed="false" type="submit">

<!--Content part-->
 <div class="layout">
      <!--Left part-->
     {% with  ads=ad_list %}
      <div class="main">
          <!--Left-hand Rotary Advertising-->
          <div  class="ad">
                <div class="ad-inner ">
                    <div class="item active">
                          <!--Advertising Big Pictures-->
                        <ul class="slidebox" id="" style="display: block;">
                            <div class="ad_slide">
                                    <ul id="slidelist" class="slideshow">
                                        {% for ad in ads %}

                                            <li style="display: block;">
                                                <a href="{{ ad.adurl }}" target="_blank" class="ad_imga">
                                                    <img src="{{ ad.pic }}"  width="880" height="300"></a>
                                        {% endfor %}

          <!--Left News List-->
          {% block left_content %}{% endblock %}
      <!--The right part-->
      <div class="side">
        <div class="author_ad ad_div">
                    <div  class="ad slide">
                            <div class="ad-inner star_div">
                                 {% for ad in ads %}
                                        {% if ad.adlocation == 'a2' %}
                                            <div class="item active">
                                                <a href="{{ ad.adurl }}" target="_blank">
                                                    <img src="{{ ad.pic }}" alt="" style="width:300px;height:300px;">
                                        {% endif %}
                                 {% endfor %}
        <!--Hot news-->

        <div class="hot module">
          <h3 class="subtitle">Hot news</h3>
            <ul  class="article_lists">
                {% for hotactile in hot_articles %}
                     <i class="top3">{{ forloop.counter }}</i>
                     <a href="{% url 'article' %}?id={{ }}">{{ hotactile.title | slice:'15'}}</a>
                {% endfor %}


        <div class="ad2">
                {% for ad in ads %}
                     {% if ad.adlocation == 'a3' %}
                       <a href="{{ ad.adurl }}" target="_blank">
                         <li><img src="{{ ad.pic }}" width="300" ></li>
                      {% endif %}
                {% endfor %}
        <!--Pay attention to us-->
        <div class="follow">
         <div class="subtitle">Pay attention to us</div>
          <div class="side_list">
             <img src="/static/images/careerqq0.8.png" >

          <!--ms-main end -->
      {% endwith %}
      {%include 'loginlayer.html' %}
  <p class="ft-copyright"></p>
 <div role="contentinfo" bosszone="footer" class="tcopyright" id="tcopyright">

    <div class="en">Copyright &copy; 2010- 2018 All Rights Reserved</div>
        <a rel="nofollow" target="_blank" href="/">Kerry Workplace Products</a>
<script type="text/javascript">
   if ($.cookie('user')) {
       $('#nologin').css('display', 'none');
       $('#logined').css('display', 'block');

Let's look at the column navigation

 <ul class="nav">
        <li class="cur"><a href="/">home page</a></li>
       {% for category in category_list %}
            {% if category|key:"id" == categoryid %}
               <li class="columnnav  cur">
            {% else %}
               <li class="columnnav">
            {% endif %}
                 <a href="{% url 'category' %}?cid={{category|key:"id" }}">{{category|key:"title" }}</a>
       {% endfor %}

First, we take out the classification data. Because the category_list data is a dictionary, we need to write a filter.
Create a new python package named template tags under the same level of article directory, and create a new python file named dictfilter.

from django import template

register = template.Library()
def key(d, key_name):
    value = 0
        value = d[key_name]
    except KeyError:
        value = 0
    return value

Here we pass a dictionary and a key name into the key, and we can get the corresponding value.
So in index.html, you just need to write the left part of the news list.

{% extends 'base.html' %}
{% load staticfiles %}
{% block left_content %}
    <div class="article_div module">
        <ul id="new_div">
        {% if  article_list %}
          {% for article in article_list %}
              <li class="news">
                    <div class="flag">Recommend</div>
                    <a href="{% url 'article' %}?id={{ }}" target="_blank">
                    <img  src="{{ article.pic }} " class="pic"></a>
                    <div class="detail">
                        <div class="dtitle">
                            <a  href="{% url 'article' %}?id={{ }}" target="_blank"><h2>{{ }}-{{ article.title }}</h2></a>
                        <div class="desc">{{ article.content|striptags|safe|slice:"80" }}</div>
                        <div class="info">
                            <img src="/static/images/neter.jpg" class="img_small"><span>{{ }}</span>
                            <div class="pv">
                               <span class="push-time">{{ article.publish_date |date:"Y-m-d H:i:s"}}</span><span class="column">
                               <a href="/">{{ article.item.title }}</a>&nbsp;</span>
           {% endfor %}
        {% else %}
         <div><img style="width:200px;padding-left:280px; " src="/static/images/nodata1.png"></div>
        {% endif %}
    {% include 'page.html' %}
{% endblock %}

7. Configuring urls

from django.contrib import admin
from django.urls import path, re_path
from artcile.views import *

urlpatterns = [
    re_path(r'^$', index, name='index'),
    path('category/', category, name='category'),
    path('article/', article, name='article'),
    path('search/', search, name='search'),

When you open the browser:, you can see news categories, news lists, advertisements, broadcast maps, hot news and pay attention to us.

Keywords: Django Python Javascript JSON

Added by CWebguy on Mon, 16 Sep 2019 09:20:01 +0300