Django uses forms to manipulate databases

Source: Internet
Author: User
Tags sql injection

Objective
    1. Goal: Implement Django to submit data via the form's get and post methods, and add to the database.
    2. OS:WIN10 x64
    3. django:1.11.8
    4. python:3.6
    5. A complete example of this article: a complete example;

Although the system and software used have no effect, let's give it a try.

Second, the realization of ideas
    • Considering from the user's point of view
      1. Access a URL, return to fill out the form page;
      2. Fill in the information on the form page and submit it;
      3. If the submission is successful, return to the submission Success page and provide a link to return to the Add page and book list;
      4. If the submission fails, return to the operation failed page and provide a jump to continue to add links;
    • From the developer perspective
      1. The user requests a URL, passing a page to the user;
      2. When the user submits the data, it is necessary to judge whether the field is lawful, and the legal is allowed to submit; The rule of law indicates which item is illegal and prompts the user to modify;
      3. After the user commits successfully, the database is modified, and if the operation succeeds, the successful page is passed; otherwise, the failed page is returned;
      4. Continue to wait for other URL requests from the user.
Third, the realization step

Next, it will be implemented from the developer's point of view.
Suppose there is a scenario where the librarian needs to enter the books and the author's information into the database, the book only has the title attribute, and the author has the name and age attributes.

1. User access URL, pass a page to the user
    • Adding routes in the urls.py file
= [    # 以上还有很多url路由,这里仅列出需要的路由    ## 利用表单增加图书,实现前台与数据库交互    url(r‘^addbook/$‘, polls_views.addbook),]

The above URL matches the address http://127.0.0.1/addbook/ , and when the user accesses the address, a page is returned to the user.

    • Return to user page bookadd.html

Add a method to the views.py file to return to page bookadd.html.

## 返回给用户页面bookadd.htmldef addbook(request):    return render(request, ‘bookadd.html‘)

Create a new bookadd.html file in the Templates directory and add the HTML code.

HTML code:

<! DOCTYPEHtml>lang="en">    <metacharset="UTF-8">    <title>Add Books</title>    <scriptsrc=".. /js/jquery-2.1.3.min.js "></script>    <style>*{            margin: 0;            padding: 0;    </style><body>            <form action= "/addbooktodatabase/" method= "Get" name= "Addbook" >        <p><span> title: </span><input type= "Text" placeholder= "title" name= "Book_name" ></p>        <p><span></span><input type= "Text" placeholder= "Author" name= "Author" ></p>        <p><span> author Age: </span><input type= "Text" placeholder= "Author age" name= "Author_age" ></p>        <input type= "Reset" >&nbsp;&nbsp;&nbsp;&nbsp;<input type= "Submit" value= "Add" >    </form>        <form action= "/addbooktodatabase/" method= "POST" name= "Addbook" >        {% Csrf_token %}<p><span> title: </span><input type="Text"Placeholder="title"Name="Book_name"></p> <p><span></span><input type="Text"Placeholder="Author"Name="Author"></p> <p><span> author Age: </span><input type="Text"Placeholder="Author age"Name="Author_age"></p> <input type="Reset">&nbsp;&nbsp;&nbsp;&nbsp;<input type="Submit"Value="Add"> </form></body>

The display results are as follows:

    • Determine if the operation is legitimate on the user's local page

Using JavaScript or jquery to make judgments, this implementation method is many, no longer repeat.

    • The user submits successfully, the background passes to the specified URL, updates the database

To add a URL route to the urls.py file

= [    # 以上还有很多url路由,这里仅列出需要的路由    ## 处理表单提交的数据,实现前台与数据库交互     url(r‘^addbooktodatabase/‘, polls_views.addbooktodatabase),]

Adding update database methods in views.py

# 向图书馆增加数据GET或POST方法方法def addbooktodatabase(request):    # 获取参数book_name,author,author_age    if request.method == "GET":        book_name = request.GET["book_name"]        author_name = request.GET["author"]        author_age = request.GET["author_age"]    else:        book_name = request.POST["book_name"]        author_name = request.POST["author"]        author_age = request.POST["author_age"]    ## 先增加作者信息    from polls.models import Person    person = Person()    person.name = author_name    person.age = author_age    person.save()    ## 增加图书信息    from polls.models import Book    bookadded = Book(name=book_name)    # 保存修改    bookadded.person_id = person.id    bookadded.save()    # 重定向到添加成功页面    from django.http import HttpResponseRedirect    return HttpResponseRedirect(‘/addok/‘)
    • Back to Page addok/html

To add a URL route to the urls.py file

= [    # 以上还有很多url路由,这里仅列出需要的路由    # 添加成功后返回添加成功页面addok    url(r‘^addok/‘, polls_views.addok),]

Create a new addok.html file in the Templates directory and add the HTML code.

HTML code:

<! DOCTYPEHtml>lang="en">    <metacharset="UTF-8">    <title>Add success</title>    <style>*{            margin: 0;            padding: 0;        }A{            text-decoration:None;        }    </style><body>    <div>        <p>Add book success</p>        <p><ahref="/addbook/">Continue to add</a></p>        <p><ahref="/booklist/">View List of Books</a></p>    </div></body>

The display results are as follows:

    • Pass booklist.html page when user clicks "View book list"

Booklist.html has been implemented in another blog post, please refer to: Using the URL method in Django to automatically generate a hyperlink address for address dynamic stitching

The display results are as follows:

You can see that the book "Outlaws of the Marsh has been added successfully."

Iv. Summary
    1. A complete example of this article: a complete example;
    2. Limited capacity, welcome to the point of error.

Attention:

    1. Here does not implement the security of the page detection, can be achieved by JS or jquery by itself;
    2. When receiving data, the get and post methods need to be judged because of the different values of Get and post methods;
    3. To prevent malicious SQL injection, the content fields entered by the user should also be detected.

Django uses forms to manipulate databases

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.