12.3 APP
12.31 Create APP
A Django project can be divided into many APP s to isolate code from different functional modules.
Create an APP from the command line:
python3 manage.py startapp app01
Create an APP, remember to tell Django the name of the app, add in settings.py:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'app01',#perhaps'app01.apps.App01Config', ]
ORM in 12.32 Django
Django project uses MySQL database
1. In the settings.py file of the Django project, configure database connection information: Tell Django which database to connect to.
DATABASES = { "default": { "ENGINE": "django.db.backends.mysql", "NAME": "db6", # You need to create the database manually first "USER": "root", "PASSWORD": "", "HOST": "127.0.0.1", "PORT": 3306 } }
2.Django uses MySQLdb module to connect database by default, but MySQLdb does not support in Python 3, so:
Write the following code in the _init_ py file of the folder with the same name as the Django project. Tell Django to connect MySQL database instead of MySQLdb using pymysql module:
import pymysql pymysql.install_as_MySQLdb()
3. Define classes in the app/models.py file. Be sure to inherit models.
from django.db import models class User(models.Model): id = models.AutoField(primary_key=True) # Self increasing primary key name = models.CharField(max_length=16) # varchar(16) pwd = models.CharField(max_length=128) # varchar(128) # Press class Publisher(models.Model): id = models.AutoField(primary_key=True) # Self increasing primary key name = models.CharField(max_length=16) # varchar(16) # Name of Publishing House #def __str__(self): #Definition _str_ is the field in each row that you can see when you print the object of the table # return (self.id,self.name) # book class Book(models.Model): id = models.AutoField(primary_key=True) # Self-increasing primary key title = models.CharField(max_length=32) # Titles of books varchar(32) publisher = models.ForeignKey(to="Publisher") # Foreign key Association Publisher This form # author class Author(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=16) books = models.ManyToManyField(to="Book") # ORM Creating multiple-to-multiple fields automatically creates a third table in the database id Author_id,Book_id
Use the command line to perform the creation of tables:
1. Python 3 management. py makemigrations - > Register the modifications to models.py in a small book 2. Python 3 management. py migrate - > translates the changes into SQL statements to execute in the database
4. Write the corresponding function publisher_list/ in urls.py in app/views.py file; / add_publisher/ the corresponding function add_publisher
Correspondence in urls.py:
from django.conf.urls import url from django.contrib import admin from app01 import views # Corresponding relation urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/', views.login), url(r'^publisher_list/', views.publisher_list), # Press List url(r'^add_publisher/', views.add_publisher), # Add Publishing House url(r'^delete_publisher/', views.delete_publisher), # Delete Publishing House url(r'^edit_publisher/', views.edit_publisher), # Editorial Press url(r'^book_list/', views.book_list), # List of books url(r'^add_book/', views.add_book), # Add books url(r'^delete_book/', views.delete_book # Delete books url(r'^edit_book/', views.edit_book), # Editing books url(r'^author_list/', views.author_list), # Author list url(r'^add_author/', views.add_author), # Add author url(r'^delete_author/', views.delete_author), # Delete author url(r'^edit_author/', views.edit_author), # Editor author url(r'^$', views.publisher_list) # If none of the above correspondences can be found, they will match the publishing house pages. ]
app/views.py:
12.321 Functional Logic of Publishing House
from django.shortcuts import HttpResponse, render, redirect from app01 import models # Show a list of Publishers def publisher_list(request): ret = models.Publisher.objects.all() # Remove all list of data objects from the database #print(ret) return render(request, "publisher_list.html", {"publisher_list": ret}) #Adding Publishing House Function def add_publisher(request): # Depending on the method of request, do different things,add_publisher.html Use POST Method if request.method == "POST":#request.method What you get is the method of the request.(GET,POST...Must be capitalized) #request.POST(Dictionaries)Obtain POST All data submitted new_publisher_name = request.POST.get("publisher_name") models.Publisher.objects.create(name=new_publisher_name)#Create objects and encapsulate properties(Insert a row of data) #Or instantiate an object with a class itself:obj=models.Publisher(name=new_publisher_name) obj.save() #Let users jump to publisher_list.html,After displaying the new data publisher_list.html page return redirect("/publisher_list/") return render(request, "add_publisher.html") # Delete Publishing House Functions def delete_publisher(request): #print(request.method) #print(request.GET) delete_id = request.GET.get("id") #Get the publisher that the user wants to delete id value #print(delete_id) obj = models.Publisher.objects.get(id=delete_id)#according to id Deserving Objects obj.delete() #Delete data return redirect("/publisher_list/") #Allow users to re-access publisher_list.html Update page # Functions of Editorial Publishing House def edit_publisher(request): #edit_id = request.GET.get("id")If the user submits for use URL Splicing id,Then from URL Take inside id parameter request.GET.get("id") if request.method == "POST": #If it is post Request, indicating that the user has edited and submitted the revised new data to the server edit_id = request.POST.get("edit_id") # Get the revised publisher id new_name = request.POST.get("name") # Get the name of the revised Publishing House edit_obj = models.Publisher.objects.get(id=edit_id)#adopt id Find data row objects edit_obj.name = new_name edit_obj.save() #Save the changes and submit the database return redirect("/publisher_list/") # Successful modification, let the user jump to the publisher list page, update the page #If not post Request, then return edit_publisher.html Pages for users to modify publishing houses edit_id = request.GET.get("id") #First get the editor's Publishing House ID value obj = models.Publisher.objects.get(id=edit_id) #according to id Value to the database to find the corresponding row data object return render(request, "edit_publisher.html", {"publisher": obj})#Display the publisher whose data you want to edit and wait for the user to edit
templates/publisher_list.html:
<body> <table border="1"> <thead> <tr> <th>#</th> <th>Name of Publishing House</th> </tr> </thead> <tbody> {% for publisher in publisher_list %} <tr> <td>{{ publisher.id }}</td> #{forloop.counter} counts the number of data bars in the table, thereby deleting and updating the id <td>{{ publisher.name }}</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> edit </a> <a class="btn btn-danger btn-sm" href="/delete_publisher/?id={{ publisher.id }}"> <i class="fa fa-trash-o fa-fw" aria-hidden="true"></i>delete </a> </td> </tr> {% endfor %} </tbody> </table> </body>
templates/add_publisher.html:
<body> <h1>Add new Publishers</h1> <form action="/add_publisher/" method="post"> <input type="text" name="publisher_name"> <input type="submit" value="Submission"> </form> </body>
templates/edit_publisher.html:
#If#Action="/ edit_publisher/? Id={{publisher. id}}" then the ID parameter is taken from the URL with request.GET.get(). <form class="form-horizontal" action="/edit_publisher/" method="post"> <input type="text" name="edit_id" value="{{ publisher.id }}" class="hide">#Hide the input box that gets the id <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Name of Publishing House</label> <div class="col-sm-9"> <input type="text" class="form-control" id="inputEmail3" name="name" placeholder="Name of Publishing House" value="{{ publisher.name }}">#Submit the name of the publisher </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-default">Submission</button> </div> </div> </form>
12.322 Functional Logic of Books
from django.shortcuts import HttpResponse, render, redirect from app01 import models # Book List Function def book_list(request): ret = models.Book.objects.all() #Go to the database and query all book objects return render(request, "book_list.html", {"book_list": ret})#Fill the page with data and send it to the client # Adding Book Functions def add_book(request): if request.method == "POST": #If it is POST Request indicates that the user has added a new book and associated Publishing House book_name = request.POST.get("book_name") # Add the name of the new book publisher_id = request.POST.get("publisher_id") # Publishers that add new book associations id value models.Book.objects.create(title=book_name, publisher_id=publisher_id) #publisher_obj = models.Publisher.objects.get(id=publisher_id)#Find the associated publisher object first according to the id value #models.Book.objects.create(title=book_name, publisher=publisher_obj) return redirect("/book_list/") # Create success, let users jump to the book list page, refresh data # Get all the publishing house data and render it on the page. select Label for user's choice ret = models.Publisher.objects.all() return render(request, "add_book.html", {"publisher_list": ret}) # Functions to Delete Books def delete_book(request): delete_book_id = request.GET.get("id") # from URL It contains books to be deleted. ID models.Book.objects.get(id=delete_book_id).delete()# Delete from the database return redirect("/book_list/") # Delete successfully, jump to book list page, refresh data # Functions for Editing Books def edit_book(request): if request.method == "POST": # If it is POST The request table name is that the user modifies the data and submits it to the back end. new_book_title = request.POST.get("book_title") # Retrieve data submitted by users new_publisher_id = request.POST.get("publisher_id") book_id = request.GET.get("id") #Obtain URL Current Editor of Books in the ____________ id book_obj = models.Book.objects.get(id=book_id)# according to id Remove the object of the book to be edited book_obj.title = new_book_title book_obj.publisher_id = new_publisher_id book_obj.save() # Save the changes to the database return redirect("/book_list/") # After the modification, let the user jump back to the book list page # Returns a page that allows users to edit data edit_book_id = request.GET.get("id") # Take the edited books. id value edit_book_obj = models.Book.objects.get(id=edit_book_id) # Get the object of the book you want to edit publisher_list = models.Publisher.objects.all() # Go to the database to query all publishing house data at present return render(request,"edit_book.html",{"book": edit_book_obj,"publisher_list":publisher_list})
templates/book_list.html:
<table class="table table-striped table-bordered"> <thead> <tr> <th>Serial number</th> <th>Titles of books</th> <th>Name of Publishing House</th> <th>operation</th> </tr> </thead> <tbody> {% for book in book_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ book.title }}</td> <td>{{ book.publisher.name}}</td># book.publisher gets the row data object of the publisher associated with the foreign key (id). <td class="text-center"> <a class="btn btn-info btn-sm" href="/edit_book/?id={{ book.id }}"> <i class="fa fa-pencil fa-fw" aria-hidden="true"></i> edit </a> <a class="btn btn-danger btn-sm" href="/delete_book/?id={{ book.id }}"> <i class="fa fa-trash-o fa-fw" aria-hidden="true"></i> delete </a> </td> </tr> {% endfor %} </tbody> </table>
templates/add_book.html:
<form class="form-horizontal" action="/add_book/" method="post"> <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Titles of books</label> <div class="col-sm-9"><input type="text" class="form-control" id="inputEmail3" name="book_name" placeholder="Titles of books"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Name of Publishing House</label> <div class="col-sm-9"> <select class="form-control" name="publisher_id"> {% for publisher in publisher_list %} <option value="{{ publisher.id }}"> {{ publisher.name }} </option> {% endfor %} </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"><button type="submit" class="btn btn-default">Submission</button> </div> </div> </form>
templates/edit_book.html:
#action="" The default URL is used here, that is, / edit_book/? Id={book.id}} before inheritance. #perhaps#Action="/ edit_publisher/? Id={{publisher. id}}" then the ID parameter is taken from the URL with request.GET.get(). <form class="form-horizontal" action="" method="post"> #Hide the book to be edited and send the id to the back end. In order to find the book to be modified in the back end, it is convenient to modify it. #<input type="text" value="{{ book.id }}" name="book_id" class="hide"> #Display the name of the book and the name of the publisher to be modified in the input box and drop-down box in advance. <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Titles of books</label> <div class="col-sm-9"> <input type="text" class="form-control" id="inputEmail3" name="book_title" value="{{ book.title }}" placeholder="Titles of books"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Name of Publishing House</label> <div class="col-sm-9"> <select class="form-control" name="publisher_id"> # If the current circulation to the publisher is equal to the publisher associated with the book, add selected to indicate that the pre-selected publisher {% for publisher in publisher_list %} {% if publisher == book.publisher %} <option value="{{ publisher.id }}" selected>{{ publisher.name }}</option> {% else %} <option value="{{ publisher.id }}">{{ publisher.name }}</option> {% endif %} {% endfor %} </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-default">Submission</button> </div> </div> </form>
12.323 On Author's Functional Logic
# Author list function def author_list(request): authors = models.Author.objects.all() # Query all author data from the database and display it on the page. # author_obj = models.Author.objects.get(id=1) # print(author_obj.books.all()) Express id=1 Objects of all books written by authors return render(request, "author_list.html", {"author_list": authors}) # Adding Author Functions def add_author(request): if request.method == "POST": new_author_name = request.POST.get("author_name") # Get the name of the new author. models.Author.objects.create(name=new_author_name)# Create a new author record in the database return redirect("/author_list/") # After creating the author, let the user jump to the author list page # Return to a page for users to fill in new author information return render(request, "add_author.html") # Delete Author Function def delete_author(request): delete_author_id = request.GET.get("id") # from URL It contains the author's to be deleted. ID models.Author.objects.get(id=delete_author_id).delete()# Find the author in the database and delete it return redirect("/author_list/") # After deleting successfully, jump back to the author list page # Editing Author Function def edit_author(request): if request.method == "POST": # If the message is POST Request, should get the data submitted by the user edit_author_id = request.POST.get("author_id") # Editor's Author id # Take a new name and a new book id new_author_name = request.POST.get("author_name") new_book_ids = request.POST.getlist("book_ids") # If the submitted data is multiple values (optional) select/Multiple choice checkbox)Then use getlist Fetch list # print(request.POST) # print(edit_author_id, new_author_name, new_book_ids) # To edit authors and corresponding books edit_author_obj = models.Author.objects.get(id=edit_author_id)# Get the Editor's Author Object edit_author_obj.name = new_author_name # Revise author's name edit_author_obj.save() # Revision of books written by authors edit_author_obj.books.set(new_book_ids) #Adoption of new books id Replace the author's books and submit them to the database return redirect("/author_list/") # When the modification is complete, jump to the Author List page # Return a page for users to edit edit_author_id = request.GET.get("id") # from URL It contains the author's to be edited. id parameter edit_author_obj = models.Author.objects.get(id=edit_author_id)# Get the author object to edit book_list = models.Book.objects.all() # Get all the book object information return render(request,"edit_author.html",{"author": edit_author_obj,
templates/author_list.html:
<div class="col-md-3 col-sm-6 pull-right add-btn"> <button data-target="#myModal" data-toggle="modal" class="btn btn-success pull-right">Newly added </button> <a href="/add_author/" class="btn btn-info pull-right">New page addition </a> </div> <table class="table table-striped table-bordered"> <thead> <tr> <th>Serial number</th> <th>Author name</th> <th>Work</th> <th>operation</th> </tr> </thead> <tbody> {% for author in author_list %}#{"author_list": authors} <tr> <td>{{ forloop.counter }}</td> <td>{{ author.name }}</td> <td> #Show all the books associated with this author in this column. {% for book in author.books.all %}#List of Book Objects {% if forloop.last %} <{{ book.title }}> {% else %} <{{ book.title }}>, {% endif %} {% empty %} No works {% endfor %} </td> <td class="text-center"> <a class="btn btn-info btn-sm" href="/edit_author/?id={{ author.id }}"> <i class="fa fa-pencil fa-fw" aria-hidden="true"></i>edit </a> <a class="btn btn-danger btn-sm" href="/delete_author/?id={{ author.id }}"> <i class="fa fa-trash-o fa-fw" aria-hidden="true"></i>delete </a> </td> </tr> {% endfor %} </tbody> </table>
templates/add_author.html:
<form class="form-horizontal" action="/add_author/" method="post"> <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Author name</label> <div class="col-sm-9"> <input type="text" class="form-control" id="inputEmail3" name="author_name" placeholder="Author name"> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-default">Submission</button> </div> </div> </form>
templates/edit_author.html:
<form class="form-horizontal" action="" method="post">#action="" defaults to the current URL <input type="text" value="{{ author.id }}" name="author_id" class="hide"> <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Author name</label> <div class="col-sm-9"> <input type="text" class="form-control" id="inputEmail3" name="author_name" value="{{ author.name }}" placeholder="Author name"> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-sm-3 control-label">Work</label> <div class="col-sm-9"> <select class="form-control" name="book_ids" multiple> {% for book in book_list %} #book_list All Book Objects #Author: the author to be edited, author.books.all: all book objects of the author to be edited {% if book in author.books.all %} # If the current book is in the author's book <option value="{{ book.id }}" selected>{{ book.title }}</option> {% else %} <option value="{{ book.id }}">{{ book.title }}</option> {% endif %} {% endfor %} </select> </div> </div> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <button type="submit" class="btn btn-default">Submission</button> </div> </div> </form>