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

Project source download: https://github.com/Cherish-sun/NEWS/tree/master

Front-end System Architecture Diagram

I. Creating Front-end Projects and Applications

django-admin.py startproject newsapi
python manage.py startapp article

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

INSTALLED_APPS = [
    ...
    'artcile',
]

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://python.org/') <http.client.HTTPResponse object at 0x00000048BC908> HTTPResponse type
    page = response.read()
    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'http://www.lagou.com/zhaopin/Python/?labelWords=label'
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'http://www.lagou.com/zhaopin/Python/?labelWords=label',
'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.

views.py

1. Import package

from urllib import request, parse

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

# Create your views here.

PAGESIZE = 5

2. Introduce all API s

category_url = 'http://127.0.0.1:8005/category/'
articles_url = 'http://127.0.0.1:8005/articleList/'
hotarticles_url = 'http://127.0.0.1:8005/hot_articleList/'
ad_url = 'http://127.0.0.1:8005/ad/'
items_url = 'http://127.0.0.1:8005/item/'

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
    try:
        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')
        else:
            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:
        print(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.

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                '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):
    pass

# search
def search(request):
    pass    


# Classification page
def category(request):
    pass
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>
<html>
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<title></title>
<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 %}

</head>
<body>
  <!--Column navigation-->
<div class="header">
    <div class="layout logo">
        <a href="http://www.careeru.cn/" 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>
                   </li>

           {% endfor %}

        </ul>
        <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>
          <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>
          </div>
     </div>
        <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">
        </form>

    </div>
</div>
<!--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>
                                            </li>
                                        {% endfor %}
                                    </ul>

                             </div>
                        </ul>
                    </div>
                </div>
          </div>
          <!--Left News List-->
          {% block left_content %}{% endblock %}
      </div>
      <!--The right part-->
      <div class="side">
          <!--Advertisement-->
        <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;">
                                                </a>
                                            </div>
                                        {% endif %}
                                 {% endfor %}
                             </div>
                    </div>
        </div>
        <!--Hot news-->

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

            </ul>
        </div>

        <!--Advertisement-->
        <div class="ad2">
           <ul>
                {% for ad in ads %}
                     {% if ad.adlocation == 'a3' %}
                       <a href="{{ ad.adurl }}" target="_blank">
                         <li><img src="{{ ad.pic }}" width="300" ></li>
                       </a>
                      {% endif %}
                {% endfor %}
          </ul>
        </div>
        <!--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" >
          </div>

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

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

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>
               </li>
       {% endfor %}
    </ul>

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()
@register.filter
def key(d, key_name):
    value = 0
    try:
        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>
                    <div class="flag">Recommend</div>
                    <a href="{% url 'article' %}?id={{ article.id }}" target="_blank">
                    <img  src="{{ article.pic }} " class="pic"></a>
                    <div class="detail">
                        <div class="dtitle">
                            <a  href="{% url 'article' %}?id={{ article.id }}" target="_blank"><h2>{{ article.id }}-{{ article.title }}</h2></a>
                        </div>
                        <div class="desc">{{ article.content|striptags|safe|slice:"80" }}</div>
                        <div class="info">
                            <img src="/static/images/neter.jpg" class="img_small"><span>{{ article.author.username }}</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>
                            </div>
                        </div>
                    </div>
                </div>
            </li>
           {% endfor %}
        {% else %}
         <div><img style="width:200px;padding-left:280px; " src="/static/images/nodata1.png"></div>
        {% endif %}
         </ul>
    </div>
    {% include 'page.html' %}
{% endblock %}

7. Configuring urls

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

urlpatterns = [
    path('admin/', admin.site.urls),
    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: http://127.0.0.1:8000, 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