python crawls stories to Mysql and uses Django framework to do a search rendering interface [django search rendering stage]

Environment: pycharm 3.6 MySQL Django HTML JS

1. Creating a virtual environment: python-m venv bxwx001

2. CMD enters the Scripts directory and enters the instruction: activate to activate the virtual environment

3. Download the package needed by the project to the virtual environment pip install django/pymysql...
4. Create a django project, switch to django start project bxwx under the virtual environment directory, and create a django project named bxwx.

5. Switch to the bxwx directory and create the app instruction: Python management.py startapp bookinfo
6. Because the django framework has its own background, you can directly create a super administrator: Python management. py create superuser, which will allow you to enter an account, default python, enter a password, as required, the password is invisible.
7. Enter the project and see the following documents

I won't talk about the file function here. I'm not very proficient yet. I can only use it.
Technological process:
a. Project bxwx/settings to make system configuration including language, time zone, database and other modifications.
b. Since the framework default sqlite is not used, it needs to be in bxwx/init.py

c. Write models.py files based on analysis data tables and presentation
d. Register in admin file according to the classes of the models file, generate Python management. py makemigrations, and execute migrations

e. After migration, a 0001_initial.py file is generated in migrations under app, which records how to generate the data table and defines the fields of the data table.

f. Next you need to design views and templates, configure them in bxwx/urls, and point to the URLs of app

g. Define various views (functions) in app views and call corresponding templates. Modeling template files under project bxwx, store all app template files (.html), edit and wait for view views call.

models.py

from django.db import models

# Create your models here.
class Bookinfo(models.Model):
    book_id=models.CharField(max_length=20,primary_key=True)
    book_name=models.CharField(max_length=20)
    book_author=models.CharField(max_length=20)
    book_introduce=models.CharField(max_length=200)
    book_update_time=models.CharField(max_length=20)
    img_src=models.CharField(max_length=100)
    def __str__(self):
        return self.book_name

class Bookinfo1(models.Model):
    book_id = models.CharField(max_length=20,)
    book_name = models.CharField(max_length=20,primary_key=True)
    book_author = models.CharField(max_length=20)
    book_introduce = models.CharField(max_length=200)
    book_update_time = models.CharField(max_length=20)
    img_src = models.CharField(max_length=100)
    def __str__(self):
       return self.book_name

views.py

from django.shortcuts import render
from bookinfo.models import *

# Create your views here.
def index(request):
    return render(request,'bookinfo/index1.html')

def bookinfo(request,keyWords):
  try:
    book=Bookinfo.objects.get(book_id=keyWords)
    context={'b':book}
    return render(request,'bookinfo/bookinfo.html',context)
  except:
      return render(request, 'bookinfo/error.html')

def bookinfoCN(request,keyWords):
    try:
     book = Bookinfo1.objects.get(book_name=keyWords)
     context={'b':book}
     return render(request, 'bookinfo/bookinfo.html', context)
    except:

      return render(request, 'bookinfo/error.html')

settings.py

"""
Django settings for bxwx project.

Generated by 'django-admin startproject' using Django 2.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'b*x3vav&e!=z42$1yji8^*y3_+(qi4*-@@a9v3_ba5@_w&su0&'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'bookinfo',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'bxwx.urls'

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',
            ],
        },
    },
]

WSGI_APPLICATION = 'bxwx.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bxwx1',
        'USER':'root',
        'PASSWORD':'123456',
        'HOST':'localhost',
        'PORT':3306
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'zh-hans'

TIME_ZONE = 'Asia/Shanghai'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

Search page html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Novel query</title>
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
function get_url(){
debugger;
     var sea = $('#keyWord').val();
     window.location.href='http://127.0.0.1:8000/index/'+sea+'/';
}
</script>

<style type="text/css">
    #box{
        width: 422px;
        margin: 100px auto;
        font-family: 'Microsoft YaHei';
        font-size: 14px;
    }
    input{
        width: 300px;
        border: 1px solid #e2e2e2;
        height: 40px;
        background-size: 25px;
        background-position:5px center;
        padding:0 0 0 40px;
    }
    button{
        width: 80px;
        height: 42px;
        float: right;
        background: black;
        color:  white;
        text-align: center;
        line-height: 32px;
        cursor: pointer;
    }

</style>

</head>

<body background="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1568266542099&di=9b453f4d5fe95f3e6af51752787d5aae&imgtype=0&src=http%3A%2F%2Fimg3.jc001.cn%2Fimg%2F285%2F1550285%2F1311%2F1352830e1352a80.jpg">

<div id="box">
<input id="keyWord"  type="text" value="" placeholder="Please enter the key words of the novel.">
<button id="serach" onclick="get_url()">search</button>
</div>
</body>
</html>

Details of the novel are displayed on the page:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Novel details</title>
</head>
<body background="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1568266542099&di=9b453f4d5fe95f3e6af51752787d5aae&imgtype=0&src=http%3A%2F%2Fimg3.jc001.cn%2Fimg%2F285%2F1550285%2F1311%2F1352830e1352a80.jpg">

<table border="1" width="1320px" >
<tr>
    <th width="200px">Fiction Poster</th>
    <th width="40px">book_id</th>
    <th width="85px">The name of the novel</th>
    <th width="75px">Fiction author</th>
    <th width="820px">Introduction to Novels</th>
    <th width="100px">Recent updates</th>

  </tr>
  <tr>
      <td><img src="{{b.img_src}}" ></td>
      <td>{{b.book_id}}</td>
      <td>{{b.book_name}}</td>
      <td>{{b.book_author}}</td>
      <td>{{b.book_introduce}}</td>
      <td>{{b.book_update_time}}</td>


  </tr>

</table>


</body>
</html>

The search interface is as follows: it can be queried by novel book_id and novel name. If the data can not be found, it will jump to the specified interface.

Now let's try:


Then try the name of the novel:


Enter a novel that cannot be found in a database:


Enter any character at will:


At this point, the search function has been successfully completed and displayed in the front section of the interface.
See the previous article for database data sources:
python crawls stories to Mysql and uses django framework to do a search and presentation interface [crawler-mysql phase]

Tags: Django Python MySQL Database

Posted on Wed, 11 Sep 2019 22:47:54 -0700 by SuprSpy79