Table of Contents
{{ book.btitle }}
{{ hero.hname }}
Home Backend Development Python Tutorial Implementation method of Django book character adaptation system in python (front-end)

Implementation method of Django book character adaptation system in python (front-end)

Nov 15, 2018 pm 03:23 PM
mysql python windows

The content of this article is about the implementation method (front-end) of the Django book character adaptation system in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Django adds routing

Like flask, django also needs to use routing to associate the URL with the code to be executed on the server side.

The same thing about both is that they can turn an ordinary function into a view function. The difference is that flask uses the decorator @app.route() to define routes, while django uses regular expressions to define routes.

Operation: Create a new urls.py file in the book project we created

#FristDjango\book\urls.py
from django.conf.urls import url
from django.contrib import admin
from book.views import index,detail
urlpatterns = [
    url(r'^$',index),   #http://127.0.0.1:9099/
    url(r'book/(?P<id>\d+)/$',detail)   #http://127.0.0.1:9099/book/1/
]</id>
Copy after login

Modify the setting.py file of the main project

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'',include('book.urls'))    

]
Copy after login

View function You can write it as you like, now it is only used for testing

#FristDjango\book\views.py
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
def index(request): #django不同于flask,flask默认请求方式是request,而django里面的请求对象必须作为参数接收
    return  HttpResponse('ok')

def detail(request,id):
    return HttpResponse('%s is ok' %(id))
Copy after login

Implementation method of Django book character adaptation system in python (front-end)

^ matches the beginning of the URL path, $ matches the end of the URL path. There is nothing in the middle, indicating that this regular match is the root directory, '/'.

Simple web page structure

Have tested that the web page is available, now write your own html file to implement your own project
Our web template files are placed in the application files in the templates/ directory of the main project. There may be multiple applications, so different directories are created to distinguish them.
It is necessary to achieve integration with the database. The database information managed in the background should be displayed in the foreground and the view function should be rewritten

#FristDjango\book\views.py
from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from book.models import BookInfo,HeroInfo


def index(request): #django不同于flask,flask默认请求方式是request,而django里面的请求对象必须作为参数接收
    # return  HttpResponse('ok')
    books = BookInfo.objects.all()
    return render(request,'book/index_old.html',context={
        'books':books,
    })
def detail(request,id):
    # return HttpResponse('%s is ok' %(id))
    book = BookInfo.objects.get(id=id)
    heros = book.heroinfo_set.all()
    return render(request,'book/detail_old.html',context={
        'book':book,
        'heros':heros
    })
Copy after login

The html page displayed on the homepage

# templates/book/index_old.html
nbsp;html>


    <meta>
    <title>主页</title>


Copy after login
    {% for book in books %}     
  •     

    {{ book.btitle }}

            

    {{ book.bpub_time }}

        

    {{ book.bcontent }}

        
  • {% endfor %}

The html page displayed on the book details page

# templates/book/detail_old.html
nbsp;html>


    <meta>
    <title>{{ book.btitle}}详情页</title>


    <h1 id="book-btitle">{{ book.btitle }}</h1>
Copy after login
        {% for hero in heros %}     

    {{ hero.hname }}

            

    {{ hero.hcontent }}

        {% endfor %}

Implementation method of Django book character adaptation system in python (front-end)

How to make the page look better

step1: There is too little book information, modify the book database table structure, add book summary, Book pictures
step2: Find some good-looking page files from the Internet to make modifications

注意:静态文件(CSS,JS,IMG)单独存放一个目录static/
样式文件的目录需要修改,主项目settings.py文件修改Static files
Copy after login

step1 Operation: Modify the structure of the BookInfo table in the book/models.py file and add abstracts and pictures. Create a new static/uploads/ directory to store uploaded images.

    bcontent = models.TextField(default='摘要', verbose_name='书籍摘要')
    bimg = models.ImageField(default=None, upload_to='static/uploads/')
Copy after login

Terminal execution database migration command

python manage.py makemigrations
python manage.py migrate
Copy after login

Use the administrator to log in to the background and modify the book content

step2 operation: After creating the static/directory, modify the main project settings.py file

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

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]
Copy after login

Note: There is a lot of repeated code on the homepage and details page. We create a base template and let the application template inherit from the base class to reduce the amount of code duplication.
The last modified web page is shown in the figure:

Implementation method of Django book character adaptation system in python (front-end)

Implementation method of Django book character adaptation system in python (front-end)
Project framework diagram:

Implementation method of Django book character adaptation system in python (front-end)

The above is the detailed content of Implementation method of Django book character adaptation system in python (front-end). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
MySQL: The Database, phpMyAdmin: The Management Interface MySQL: The Database, phpMyAdmin: The Management Interface Apr 29, 2025 am 12:44 AM

MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

Steps to add and delete fields to MySQL tables Steps to add and delete fields to MySQL tables Apr 29, 2025 pm 04:15 PM

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Apr 30, 2025 pm 07:24 PM

The built-in quantization tools on the exchange include: 1. Binance: Provides Binance Futures quantitative module, low handling fees, and supports AI-assisted transactions. 2. OKX (Ouyi): Supports multi-account management and intelligent order routing, and provides institutional-level risk control. The independent quantitative strategy platforms include: 3. 3Commas: drag-and-drop strategy generator, suitable for multi-platform hedging arbitrage. 4. Quadency: Professional-level algorithm strategy library, supporting customized risk thresholds. 5. Pionex: Built-in 16 preset strategy, low transaction fee. Vertical domain tools include: 6. Cryptohopper: cloud-based quantitative platform, supporting 150 technical indicators. 7. Bitsgap:

How to uninstall MySQL and clean residual files How to uninstall MySQL and clean residual files Apr 29, 2025 pm 04:03 PM

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

An efficient way to batch insert data in MySQL An efficient way to batch insert data in MySQL Apr 29, 2025 pm 04:18 PM

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

How to use MySQL functions for data processing and calculation How to use MySQL functions for data processing and calculation Apr 29, 2025 pm 04:21 PM

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Detailed explanation of the installation steps of MySQL on macOS system Detailed explanation of the installation steps of MySQL on macOS system Apr 29, 2025 pm 03:36 PM

Installing MySQL on macOS can be achieved through the following steps: 1. Install Homebrew, using the command /bin/bash-c"$(curl-fsSLhttps://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)". 2. Update Homebrew and use brewupdate. 3. Install MySQL and use brewinstallmysql. 4. Start MySQL service and use brewservicesstartmysql. After installation, you can use mysql-u

How to analyze the execution plan of MySQL query How to analyze the execution plan of MySQL query Apr 29, 2025 pm 04:12 PM

Use the EXPLAIN command to analyze the execution plan of MySQL queries. 1. The EXPLAIN command displays the execution plan of the query to help find performance bottlenecks. 2. The execution plan includes fields such as id, select_type, table, type, possible_keys, key, key_len, ref, rows and Extra. 3. According to the execution plan, you can optimize queries by adding indexes, avoiding full table scans, optimizing JOIN operations, and using overlay indexes.

See all articles