Django Learning (4) Forms to Make Databases Stronger

Posted by theex on Thu, 16 May 2019 18:12:26 +0200

_Form, tagged <form></form> in HTML, is mainly responsible for data collection in Web pages.When we browse websites, we often encounter registered accounts, account logins, etc., which is a typical application of forms.

_In Django Learning (2) Data Treasure In, we learned Django's connection to the MySQL database; in Django Learning (3) Template Customization In, we learned to use Django's templates to separate HTML design from Python code.This time, we'll learn how to use forms to manipulate MySQL databases directly on a Web page.

_We continue Django Learning (2) Data Treasure Book project, first create a new project Book, and in the Book project, create a new application books:

cd /home/vagrant/django_project/
django-admin.py startproject Book
cd ./Book
django-admin.py startapp books

_Add app to settings.py and set the path to find the database connection as MySQL and the template:

_Defines the model in models.py of books with the following code:

from django.db import models

class MYBOOK(models.Model):
    name = models.CharField(max_length=200)
    price = models.FloatField()

    def __str__(self):
       return self.name+':'+str(self.price)

_and create a new database book in MySQL, then connect the model in Django to the Book database in MySQL:

python3 manage.py makemigrations
python3 manage.py migrate

_This generates the books_mybook table in MySQL.To manipulate the books_mybook table in a web page using a form, we wrote two HTML templates, one for data insertion and query: index.html and one for query results: search_res.html.The index.html template is as follows:

<!DOCTYPE html>
<html>
    <body>

    <p>**********************************************</p>

    <p>Input name and price of a book:</p>

    <form action="/insert/" method="get">
            name: <input type="text" name="name"> <br>
            price: <input type="text" name="price"> <br>
            <input type="submit" value="Submit to MySQL">
    </form>

        <p>
        {% if name  and price%}
             <script>alert("Insert into MySQL already!Please check MySQL")</script>   
        {% endif %}
        </p>

    <p>**********************************************</p>

    <p>Query the price of a book:</p>

    <form action="/query/" method="get">
            Book name: <input type="text" name="book"> <br>
            <input type="submit" value="Query price">
    </form>

    <p>**********************************************</p>

    </body>
</html>

The_search_res.html template is as follows:

<p>You searched for: <strong>{{ query }}</strong></p>

{% if books %}
    <p>Found {{ books|length }} book{{ books|pluralize }}.</p>
    <ul>
        {% for book in books %}
        <li>Book: <strong>{{ book.name }}</strong>,   Price: <strong>{{book.price}}</strong></li>
        <br>
        {% endfor %}
    </ul>
{% else %}
    <p>No books matched your search criteria.</p>
{% endif %}

With these two templates, we have templates for web page display.Next, we need to create a view, with views.py code as follows:

from django.http import HttpResponse
from django.shortcuts import render_to_response
from books.models import MYBOOK

def index(request):
    return render_to_response('index.html')

def insert(request):
    NAME = request.GET['name']
    PRICE = float(request.GET['price'])
    MYBOOK.objects.create(name=NAME, price=PRICE)
    return render_to_response('index.html', {'name':NAME, 'price': PRICE})

def query(request):
    query = request.GET['book']
    books = MYBOOK.objects.filter(name__icontains = query)
    return render_to_response('search_res.html', {'query':query, 'books': books}

In the view above, index() loads the original index.html web page, insert() inserts the name and price information of the book, and upon submission, a dialog box appears showing "Insert into MySQL already!Please check MySQL", and query() displays the results of the query, which is a regular query that returns the names and prices of all books containing the'book'parameter, regardless of the book name for the time being.Call it nonexistent.
Finally, we just need to set up the url.py file and start the server server.The urls.py code is as follows:

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

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^form', 'books.views.index'),
    url(r'^insert', 'books.views.insert'),
    url(r'^query', 'books.views.query'),
]

_Start the server python3 manage.py runserver 8000, enter localhost:8000/form in the browser, the web page shows as follows:

_First, let's insert the information for the first book, as follows:

The message boxes that pop up are as follows:

_This completes the insertion of the first book.Follow this step and insert nine more books: [('Learning Pyspark', 35), ('Dive in Scala', 36), ('Think in Java', 46), ('An introduction to Python', 35), ('Learning Pandas', 24), ('Learn Python 7 Days', 28), ('Python GUI Programming Cookbook', 38), ('Python Data Structures and Algorithms', 45), ('PythonMachine Learning By Example', 50)].Viewed in MySQL, the table is as follows:

This inserts ten records.Then we query the web page just now, which is as follows:

Click the Query Price button and the page will be displayed as follows:

Search results are okay ~~
_This allows us to use forms to operate on databases at the web level, so forms make databases stronger ~~
_Of course, this is just a simple example of using forms, there are many unrealized functions, such as form validation, query error handling, etc. I believe that if you are smart, you will be able to achieve ~~


Reference:
1. Self-strengthening School Django Form: https://code.ziqiangxuetang.com/django/django-forms.html
2. Django_Chinese Tutorial.pdf: http://download.csdn.net/download/huangzhichang13/8177581

Topics: Django MySQL Python Database