[Python+Django] Web library management system graduation project database and system implementation source code

Front row reminder, this article has a lot of useful information. To avoid indigestion, it is recommended to eat in conjunction with the catalog.

This series of blog posts is for programmers who are about to graduate. There are three articles in the series. The writing process can be said to be almost based on the style of the graduation project catalog.

The relevant charts and screenshots are almost compiled in accordance with the requirements of the graduation thesis. Complete reading and digestion of this series of blog posts with the table of contents and format of a graduation thesis is almost like a computer graduation thesis.

Students who need the complete source code can download it themselves from CSDN:

https://download.csdn.net/download/agelee/31975262https://download.csdn.net/download/agelee/31975262

This article is the third part of the Python Web library management system graduation project. The first two parts are as follows:

For the software and system environment required for this article, please see: [Python+Django] Web Library Management System Graduation Project Development Tools and Technologies

For the database design and system functional requirements analysis of this article, please refer to: [Python+Django] System Requirements Analysis and Design of Web Library Management System Graduation Project

In this article, we will complete the database construction through the Django framework and use the Django framework pattern to implement the functions of the library management system:

The final functional structure of the system is as follows:

Function pages of each module:

Publishing House Management:

List display:

 Add new publisher:

Editing publisher:

Author management:

List display:

Add new author:

Modification author:

log in page:

registration page:

The following is the detailed implementation process of the system project:

Table of contents

1. Create a Django project

2. Database creation and connection configuration

2.1 Database creation

2.2Django database connection configuration

3.Django model definition

3.1 Create APP

3.2 Define the model

4. System front-end and functional module implementation

4.1 Front-end framework and Django related configuration

4.2 Implementation of publishing house management functions

4.2.1 Publisher list display

4.2.2 New publishing house

4.2.3 Modification by publisher

4.2.4 Publisher deletion

4.3 Author management function implementation

4.3.1 Create new, display, modify, delete author view functions

4.3.2 Modify ulrs.py mapping relationship

4.3.3 Author display page creation

4.3.4 Creation of new author page

4.3.5 Author editing page creation

4.3.6 Author deletion

4.4 Implementation of library management functions

4.4.1 Create new, display, modify and delete book view functions

4.4.2 Modify ulrs.py mapping relationship

4.4.3 Creation of book display page

4.4.4 Creation of new book pages

4.4.5 Book editing page creation

4.4.6 Book deletion

4.5 Registration and login function implementation

4.5.1 Create login and registration view functions

4.3.2 Modify ulrs.py mapping relationship

4.3.3 Login page creation

4.3.4 Registration page creation


1. Create a Django project

1. Create a new blank Pycharm project folder such as: PycharmProjects

2. Open Pycharm and enter the blank folder: PycharmProjects

3. Enter the command to create a Django project through Pycharm's Windows command line input interface to create a new project: bms

Django-admin startproject bms

2. Database creation and connection configuration

Django provides good support for various databases, including: PostgreSQL, MySQL, SQLite, and Oracle.

Django provides a unified calling API for these databases. We can choose different databases according to our business needs.

MySQL is the most commonly used database in web applications. This article uses MySQL.

This step connects the database settings to your own MySQL database and completes the creation of the database.

2.1 Database creation

Django can only operate to the data table level and cannot operate to the database level, so you need to create a database manually: bms

We can create a database via the command line:

1. Enter the bin subfolder directory of the mysql installation folder:

For example: D:\Program Files\mysql-8.0.13-winx64\bin

2. Connect to the database:

mysql -u root -p
Enter password:******

3. After successful connection and login, create a database through the command: bms

CREATE DATABASE IF NOT EXISTS bms DEFAULT CHARSET utf8;

Or create a database through the SQLlog tool: bms

After creation, you can see the corresponding database through SQLlog.

2.2Django database connection configuration

Django requires the mysql driver to use MySQL. If you have not installed the mysql driver, you can execute the following command to install it:

pip install pymysql

1. Enter the Django project bms folder

2. Open the setting.py file and find the DATABASES configuration item:

3. Modify the DATABSES configuration items as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',    # 数据库引擎
        'NAME': 'bms', # 数据库名称
        'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1 
        'PORT': 3306, # 端口 
        'USER': 'root',  # 数据库用户名
        'PASSWORD': '123456', # 数据库密码
    }
}

4. Django uses the pymysql module to connect to the mysql database:

 Introduce the module and configure it in __init__.py in the same directory as settings.py 

import pymysql


pymysql.install_as_MySQLdb()

3.Django model definition

Django models use the built-in ORM.

Object Relational Mapping (ORM for short) is used to convert data between different types of systems in object-oriented programming languages.

ORM acts as a bridge between the business logic layer and the database layer.

ORM automatically persists objects in a program to the database by using metadata that describes the mapping between the object and the database.

ORM parsing process:

1. ORM will convert Python code into SQL statements.

2. The SQL statement is transmitted to the database server through pymysql.

3. Execute the SQL statement in the database and return the results.

ORM correspondence table:

3.1 Create APP

Django stipulates that if you want to use models, you must create an app. We use the following command to create an app app01:

python manage.py startapp app01

After completion, the directory structure is as follows:

Next, find the INSTALLED_APPS item in settings.py and add the newly created app01 to the project's App list, as follows:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',               # 添加此项
)

3.2 Define the model

We previously created a blank database bms. In this step, we use Django's model to complete the creation of the database table.

Because Django has its own mapping rules between the model and the target database, if you create a data table in the database yourself, it may not necessarily comply with Django's table creation rules, resulting in the inability to establish communication between the model and the target database.

So it is best for us to create the corresponding database table through the Django model in the Django project

Define the model in the models.py file of project app01, the code is as follows:

from django.db import models

# Create your models here.


# 出版社类
class Publisher(models.Model):
    id = models.AutoField('序号', primary_key=True)
    name = models.CharField('名称', max_length=64)
    addr = models.CharField('地址', max_length=64)


# 书籍的类
class Book(models.Model):
    id = models.AutoField('序号', primary_key=True)
    name = models.CharField('名称', max_length=64, null=True)
    ISBN = models.CharField('编号', max_length=64)
    translator = models.CharField('译者', max_length=64)
    date = models.DateField('出版日期', max_length=64,blank=True)
    publisher = models.ForeignKey(to=Publisher, on_delete=models.CASCADE)  # Django中创建外键联表操作


# 作者的类
class Author(models.Model):
    id = models.AutoField('序号', primary_key=True)
    name = models.CharField('姓名', max_length=64)
    sex = models.CharField('性别', max_length=4)
    age = models.IntegerField('年龄', default=0)
    tel = models.CharField('联系方式', max_length=64)
    # 一个作者可以对应多本书,一本书也可以有多个作者,多对多,在数据库中创建第三张表
    book = models.ManyToManyField(to=Book)


# 用户的类
class LmsUser(models.Model):
    id = models.AutoField('序号', primary_key=True)
    username = models.CharField('用户名', max_length=32)
    password = models.CharField('密码', max_length=32)
    email = models.EmailField('邮箱')
    mobile = models.IntegerField('手机', max_length=11)

Enter code on the command line to create Django's built-in table structure:

python manage.py migrate 

 The following message appears, indicating success

Then enter the command on the command line to let Django know that there are some changes in our custom model, and generate a script to create a data table based on the model of our custom app:

python manage.py makemigrations app01

Finally, create the database table corresponding to the app01 model through the command:

python manage.py migrate app01

After successful execution, we can see in the database table that Django automatically generated the database table as shown below:

4. System front-end and functional module implementation

4.1 Front-end framework and Django related configuration

The front and backend of this article are not separated, and the front-end framework uses the currently popular Bootstrap 4.

Bootstrap is based on HTML, CSS, and JAVASCRIPT. It is simple and flexible, making Web development faster.

Create a new folder static in the project root directory to store the front-end template static resources, and import related front-end resources into the folder.

Create a new folder templates in the project root directory to store the front-end web page.

The directory after creation is as shown below:

Next we need to modify the DJango configuration to identify our static resources and template web page addresses.

Open the setting.py file, find the TEMPLATES configuration item and modify it as follows to identify the template web page address:

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

Then find STATIC_URL and add STATICFILES_DIRS below to identify static resource addresses:

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'static'),  # 添加此项
]

4.2 Implementation of publishing house management functions

4.2.1 Publisher list display

In this step, we follow the following steps to display the publisher list:

1. Define the function to display the publisher in the view file views.py under the app01 folder

In the function, we retrieve the list of all publishers and return the data to the display page.

# 出版社展示列表


def publisher_list(request):
    publisher = models.Publisher.objects.all()
    return render(request, 'pub_list.html', {'pub_list': publisher})

2. Configure the mapping relationship between the routing url and the function in the view in the routing file urls.py in the bms folder:

The route after configuration is completed is as follows:

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^pub_list/', views.publisher_list),    # 出版社列表
]

3. Create a new HTML file in the templates folder: pub_list.html, which will be used for the publisher’s display page.

The key code is as follows to display the publisher list.

<div class="col-md-10">
            <div class="content-box-large">
                <div class="panel-heading">
                    <div class="panel-title">出版社列表</div>
                </div>
                <div class="col-md-3 col-sm-6 pull-right add-btn">
                    <a href="/add_publisher/" class="btn btn-info pull-right">新增
                    </a>
                </div>
                <div class="panel-body">
                    <table cellpadding="0" cellspacing="0" border="0" class="table table-striped table-bordered" id="example">
                        <thead>
                        <tr>
                            <th>序号</th>
                            <th>出版社名称</th>
                            <th>出版社地址</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for publisher in publisher_list %}
                        <tr>
                            <td>{
   
   { forloop.counter }}</td>
                            <td>{
   
   { publisher.name }}</td>
                            <td>{
   
   { publisher.addr }}</td>
                            <td class="text-center">
                                <a class="btn btn-info btn-sm" href="/edit_publisher/?id={
   
   { publisher.id }}"><i
                                        class="fa fa-pencil fa-fw"
                                        aria-hidden="true"></i>编辑
                                </a>
                                <a class="btn btn-danger btn-sm" href="/drop_publisher/?id={
   
   { publisher.id }}"><i
                                        class="fa fa-trash-o fa-fw"
                                        aria-hidden="true"></i>删除
                                </a>
                            </td>
                        </tr>
                        {% endfor %}
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

4. Run the command line to start the Django server:

python manage.py runserver 0.0.0.0:8000

Enter the address in the browser: http://127.0.0.1:8000/pub_list

You can see the display page as shown below:

4.2.2 New publishing house

1. Create a new publishing house view function

# 添加出版社
def add_publisher(request):
    if request.method == 'POST':
        new_publisher_name = request.POST.get('name')
        new_publisher_addr = request.POST.get('addr')
        models.Publisher.objects.create(name=new_publisher_name, addr=new_publisher_addr)
        return redirect('/pub_list/')
    return render(request, 'pub_add.html')

2. Modify the ulrs.py mapping relationship

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^pub_list/', views.publisher_list),      # 出版社列表
    url(r'^add_pub/', views.add_publisher),     # 新增出版社
]

3. Create a new pub_add.html page for adding new publishers

The key code is as follows:

 <div class="col-md-10">
            <div class="content-box-large">
                <div class="panel-heading">
                    <div class="panel-title">新增出版社</div>
                </div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" action="/add_pub/" method="post">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="inputEmail3" class="col-sm-2 control-label">出版社名称</label>
                            <div class="col-sm-10">
                                <input class="form-control" id="inputEmail3" placeholder="出版社名称" name="name">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">出版社地址</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" placeholder="出版社地址" rows="3" name="addr"></textarea>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-primary">保存</button>
                                <button type="submit" formmethod="get" formaction="/pub_list" class="btn btn-default">返回</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

Enter the address in the browser: http://127.0.0.1:8000/add_pub

You can see the display page as shown below:

4.2.3 Modification by publisher

1. Create and modify the publisher view function

# 编辑出版社
def edit_publisher(request):
    if request.method == 'POST':
        edit_id = request.GET.get('id')
        edit_obj = models.Publisher.objects.get(id=edit_id)
        new_name = request.POST.get('edit_name')
        new_addr = request.POST.get('edit_addr')
        edit_obj.name = new_name
        edit_obj.addr = new_addr
        edit_obj.save()
        return redirect('/pub_list/')

    edit_id = request.GET.get('id')
    edit_obj = models.Publisher.objects.get(id=edit_id)
    return render(request, 'pub_edit.html', {'publisher': edit_obj})

2. Modify the ulrs.py mapping relationship

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.publisher_list),
    url(r'^pub_list/', views.publisher_list),      # 出版社列表
    url(r'^add_pub/', views.add_publisher),     # 新增出版社
    url(r'^edit_pub/', views.edit_publisher),     # 编辑出版社
]

3. Create a new pub_edit.html page for editing the publishing house

The key code is as follows:

<div class="col-md-10">
            <div class="content-box-large">
                <div class="panel-heading">
                    <div class="panel-title">编辑出版社</div>
                </div>
                <div class="panel-body">
                    <form class="form-horizontal" role="form" action="/edit_publisher/?id={
   
   { publisher.id }}" method="post">
                                                    <input type="text" name="edit_id" value="{
   
   { publisher.id }}" class="hide">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="input1" class="col-sm-2 control-label">出版社名称</label>
                            <div class="col-sm-10">
                                <input class="form-control" id="input1" placeholder="出版社名称" name="edit_name" value="{
   
   { publisher.name }}">
                            </div>
                        </div>
                        <div class="form-group">
                            <label class="col-sm-2 control-label">出版社地址</label>
                            <div class="col-sm-10">
                                <input class="form-control" id="input2" placeholder="出版社名称" name="edit_addr" value="{
   
   { publisher.addr }}">
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-offset-2 col-sm-10">
                                <button type="submit" class="btn btn-primary">保存</button>
                                <button type="submit" formmethod="get" formaction="/pub_list" class="btn btn-default">返回</button>
                            </div>
                        </div>
                    </form>
                </div>

            </div>
        </div>

Add the click-to-edit function code in pub_list.html as follows:

                                <a class="btn btn-info btn-sm" href="/edit_pub/?id={
   
   { publisher.id }}"><i
                                        class="fa fa-pencil fa-fw"
                                        aria-hidden="true"></i>编辑
                                </a>

 From the edit button in the publisher list, you can enter the editing page as shown below:

4.2.4 Publisher deletion

1. Create and delete publisher view function

# 删除出版社

def drop_publisher(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Publisher.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/pub_list/')

2. Modify the ulrs.py mapping relationship

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.publisher_list),
    url(r'^pub_list/', views.publisher_list),      # 出版社列表
    url(r'^add_pub/', views.add_publisher),     # 新增出版社
    url(r'^edit_pub/', views.edit_publisher),     # 编辑出版社
    url(r'^drop_pub/', views.drop_publisher),     # 删除出版社
]

3. Add the click-to-edit function code in pub_list.html as follows:

                                <a class="btn btn-danger btn-sm" href="/drop_pub/?id={
   
   { publisher.id }}">
                                <i
                                        class="fa fa-trash-o fa-fw"
                                        aria-hidden="true"></i>删除
                                </a>

Clicking the delete button will delete the publisher data of the corresponding line item in the list.

4.3 Author management function implementation

Refer to the final implementation code and page display of publishing house management as follows:

4.3.1 Create new, display, modify, delete author view functions

# 作者的列表
def author_list(request):
    author = models.Author.objects.all()
    return render(request, 'auth_list.html', {'author_list': author})


# 添加作者
def add_author(request):
    if request.method == 'POST':
        new_author_name = request.POST.get('name')
        new_author_sex = request.POST.get('sex')
        new_author_age = request.POST.get('age')
        new_author_tel = request.POST.get('tel')
        models.Author.objects.create(name=new_author_name, sex=new_author_sex, age=new_author_age, tel=new_author_tel)
        return redirect('/author_list/')
    return render(request, 'author_add.html')


# 删除作者
def drop_author(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Author.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/author_list/')


# 修改作者
def edit_author(request):
    if request.method == 'POST':
        edit_id = request.GET.get('id')
        edit_obj = models.Author.objects.get(id=edit_id)
        new_author_name = request.POST.get('edit_name')
        new_author_sex = request.POST.get('edit_sex')
        new_author_age = request.POST.get('edit_age')
        new_author_tel = request.POST.get('edit_tel')
        new_book_id = request.POST.getlist('book_id')
        edit_obj.name = new_author_name
        edit_obj.sex = new_author_sex
        edit_obj.age = new_author_age
        edit_obj.tel= new_author_tel
        edit_obj.book.set(new_book_id)
        edit_obj.save()
        return redirect('/author_list/')
    edit_id = request.GET.get('id')
    edit_obj = models.Author.objects.get(id=edit_id)
    all_book = models.Book.objects.all()
    return render(request, 'auth_edit.html', {
        'author': edit_obj,
        'book_list': all_book
    })

4.3.2 Modify ulrs.py mapping relationship

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.publisher_list),
    url(r'^pub_list/', views.publisher_list),      # 出版社列表
    url(r'^add_pub/', views.add_publisher),     # 新增出版社
    url(r'^edit_pub/', views.edit_publisher),     # 编辑出版社
    url(r'^drop_pub/', views.drop_publisher),     # 删除出版社
    url(r'^author_list/', views.author_list),     # 作者列表
    url(r'^add_author/', views.add_author),    # 新增作者
    url(r'^drop_author/', views.drop_author),    # 删除作者
    url(r'^edit_author/', views.edit_author),    # 编辑作者
]

4.3.3 Author display page creation

Create a new auth_list.html page to display authors

Enter the address in the browser: http://127.0.0.1:8000/a uthor_list

You can see the display page as shown below:

4.3.4 Creation of new author page

Create a new auth_add.html page for adding new authors

Click the add button on the author display page or enter the address in the browser: http://127.0.0.1:8000/add_author/

You can see the display page as shown below:

4.3.5 Author editing page creation

Create a new auth_edit.html page to modify the author

Click the edit button on the author display page

You can see the display page as shown below:

4.3.6 Author deletion

Add the author deletion code on the author display page:

                                <a class="btn btn-danger btn-sm" href="/drop_author/?id={
   
   { author.id }}"><i
                                        class="fa fa-trash-o fa-fw"
                                        aria-hidden="true"></i>删除
                                </a>

4.4 Implementation of library management functions

Refer to the final implementation code and page display of publishing house management as follows:

4.4.1 Create new, display, modify and delete book view functions

# 书籍的列表
def book_list(request):
    book = models.Book.objects.all()
    return render(request, 'book_list.html', {'book_list': book})


# 添加本书籍
def add_book(request):
    if request.method == 'POST':
        new_book_name = request.POST.get('name')
        new_book_ISBN = request.POST.get('ISBN')
        new_book_translator = request.POST.get('translator')
        new_book_date = request.POST.get('date')
        publisher_id = request.POST.get('publisher_id')
        models.Book.objects.create(name=new_book_name, publisher_id=publisher_id, ISBN=new_book_ISBN,
                                   translator=new_book_translator, date=new_book_date)
        return redirect('/book_list/')
    res = models.Publisher.objects.all()
    return render(request, 'book_add.html', {'publisher_list': res})


# 删除本书籍
def drop_book(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Book.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/book_list/')


# 编辑本书籍
def edit_book(request):
    if request.method == 'POST':
        new_book_name = request.POST.get('name')
        new_book_ISBN = request.POST.get('ISBN')
        new_book_translator = request.POST.get('translator')
        new_book_date = request.POST.get('date')
        new_publisher_id = request.POST.get('publisher_id')
        edit_id = request.GET.get('id')
        edit_obj = models.Book.objects.get(id=edit_id)
        edit_obj.name = new_book_name
        edit_obj.ISBN = new_book_ISBN
        edit_obj.translator = new_book_translator
        edit_obj.date = new_book_date
        edit_obj.publisher_id = new_publisher_id
        edit_obj.save()
        return redirect('/book_list/')
    edit_id = request.GET.get('id')
    edit_obj = models.Book.objects.get(id=edit_id)
    all_publisher = models.Publisher.objects.all()
    return render(request, 'book_edit.html', {'book': edit_obj, 'publisher_list': all_publisher})

4.4.2 Modify ulrs.py mapping relationship

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.publisher_list),
    url(r'^pub_list/', views.publisher_list),      # 出版社列表
    url(r'^add_pub/', views.add_publisher),     # 新增出版社
    url(r'^edit_pub/', views.edit_publisher),     # 编辑出版社
    url(r'^drop_pub/', views.drop_publisher),     # 删除出版社
    url(r'^author_list/', views.author_list),     # 作者列表
    url(r'^add_author/', views.add_author),    # 新增作者
    url(r'^drop_author/', views.drop_author),    # 删除作者
    url(r'^edit_author/', views.edit_author),    # 编辑作者
    url(r'^book_list/', views.book_list),     # 图书列表
    url(r'^add_book/', views.add_book),     # 新增图书
    url(r'^drop_book/', views.drop_book),     # 删除图书
    url(r'^edit_book/', views.edit_book),     # 编辑图书
]

4.4.3 Creation of book display page

Create a new book_list.html page to display authors

Enter the address in the browser: http://127.0.0.1:8000/ book_list

You can see the display page as shown below:

4.4.4 Creation of new book pages

Create a new book_add.html page to add authors

Click the add button on the author display page or enter the address in the browser: http://127.0.0.1:8000/add_book/

You can see the display page as shown below:

4.4.5 Book editing page creation

Create a new book_edit.html page to modify the author

Click the edit button on the author display page

You can see the display page as shown below:

4.4.6 Book deletion

Add the author deletion code on the author display page:

                                <a class="btn btn-danger btn-sm" href="/drop_book/?id={
   
   { book.id }}"><i
                                        class="fa fa-trash-o fa-fw"
                                        aria-hidden="true"></i>删除
                                </a>

4.5 Registration and login function implementation

Refer to the final implementation code and page display of publishing house management as follows:

4.5.1 Create login and registration view functions

# 密码加密

def setPassword(password):
    """
    加密密码,算法单次md5
    :param apssword: 传入的密码
    :return: 加密后的密码
    """
    md5 = hashlib.md5()
    md5.update(password.encode())
    password = md5.hexdigest()
    return str(password)

# 登录

def login(request):
    if request.method == 'POST' and request.POST:
        email = request.POST.get("email")
        password = request.POST.get("password")
        e = LmsUser.objects.filter(email = email).first()
        if e:
            now_password = setPassword(password)
            db_password = e.password
            if now_password == db_password:
                # return render(request, "pub_list.html")
                response = HttpResponseRedirect('/pub_list/')
                response.set_cookie("username", e.username)
                return response

    return render(request, "login.html")

# 注册

def register(request):
    if request.method == "POST" and request.POST:
        data = request.POST
        username = data.get("username")
        email = data.get("email")
        password = data.get("password")
        mobile = data.get("mobile")
        LmsUser.objects.create(
            username=username,
            email=email,
            password=setPassword(password),
            # password=password,
            mobile=mobile,
        )
        return HttpResponseRedirect('/login/')
    return render(request,"register.html")

4.3.2 Modify ulrs.py mapping relationship

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^$', views.publisher_list),
    url(r'^pub_list/', views.publisher_list),      # 出版社列表
    url(r'^add_pub/', views.add_publisher),     # 新增出版社
    url(r'^edit_pub/', views.edit_publisher),     # 编辑出版社
    url(r'^drop_pub/', views.drop_publisher),     # 删除出版社
    url(r'^author_list/', views.author_list),     # 作者列表
    url(r'^add_author/', views.add_author),    # 新增作者
    url(r'^drop_author/', views.drop_author),    # 删除作者
    url(r'^edit_author/', views.edit_author),    # 编辑作者
    url(r'^book_list/', views.book_list),     # 图书列表
    url(r'^add_book/', views.add_book),     # 新增图书
    url(r'^drop_book/', views.drop_book),     # 删除图书
    url(r'^edit_book/', views.edit_book),     # 编辑图书
    url(r'^login/', views.login),     # 登录动作
    url(r'^signup/', views.register),     # 注册页面
    url(r'^register/', views.register),     # 注册
]

4.3.3 Login page creation

Create a new login.html page to display the author

	<div class="page-content container">
		<div class="row">
			<div class="col-md-4 col-md-offset-4">
				<div class="login-wrapper">
			        <div class="box">
							<h6>登录</h6>
							<form class="content-wrap" role="form" action="/login/" method="post">
								{% csrf_token %}
			                <input class="form-control" name="email" type="text" placeholder="E-mail">
			                <input class="form-control" name="password" type="password" placeholder="Password">
								<div class="action">
									<button type="submit" class="btn btn-primary">登录</button>
								</div>
							</form>
			        </div>
			        <div class="already">
			            <p>没有账户?</p>
			            <a href="/register">注册</a>
			        </div>
			    </div>
			</div>
		</div>
	</div>

Enter the address in the browser: http://127.0.0.1:8000/ login

You can see the display page as shown below:

4.3.4 Registration page creation

Create a new register.html page for adding new authors

	<div class="page-content container">
		<div class="row">
			<div class="col-md-4 col-md-offset-4">
				<div class="login-wrapper">
			        <div class="box">
			            <form class="content-wrap" role="form" action="/register/" method="post">
			                <h6>注册</h6>
								{% csrf_token %}
			                <input class="form-control" name="username" type="text" placeholder="Username">
			                <input class="form-control" name="email" type="text" placeholder="E-mail address">
			                <input class="form-control" name="password" type="password" placeholder="Password">
			                <input class="form-control" name="mobile" type="text" placeholder="Mobile">
<!--			                <input class="form-control" type="password" placeholder="Confirm Password">-->
								<div class="action">
									<button type="submit" class="btn btn-primary">注册</button>
								</div>
							</form>
			        <div class="already">
			            <p>已有账户?</p>
			            <a href="/login">登录</a>
			        </div>
					</div>
			    </div>
			</div>
		</div>
	</div>

Click the new button on the author display page or enter the address in the browser: http://127.0.0.1:8000/register/

You can see the display page as shown below:

Guess you like

Origin blog.csdn.net/agelee/article/details/116453544