Dozens of sets of PDFs can be obtained from the private messages 007! you can get dozens of sets of PDFs Oh!
3. Django Project directory
1) urls.py: URL entry, associated to a function in the corresponding views.py (or generic Class), the access URL corresponds to a function.
2) views.py: Processing the user's request, corresponding to the urls.py, by rendering the page in the templates can display content, such as the login user name, the user requested data such as output to the Web page.
3) models.py: It is related to database operation, it is used when the data is stored or read, it can not be used when the database is not used.
4) forms.py: The form, the user enters the data to submit in the browser, to the data verification work as well as the input box generation and so on work, also may not use.
5) Templates folder: Views.py in the function rendering templates in the HTML template, the dynamic content of the Web page, you can use the cache to improve speed.
6) admin.py: Backstage, you can have a powerful background with very little code.
7) Settings.py:Django configuration file, such as DEBUG switch, static file location, etc.
5. Views and URLs
views.py:
From django.http import HttpResponse
def helloWorld (Request):
Return HttpResponse ("Hello world!")
urls.py:
From Django.conf.urls import URL
From. Import View
Urlpatterns = [
URL (r ' ^$ ', View.helloworld)
]
Start the server and access it in the browser: 127.0.0.1:8000.
Modified urls.py:
From Django.conf.urls import URL
From. Import View
Urlpatterns = [
URL (r ' ^helloworld$ ', View.helloworld)
]
Start the server and access it in the browser: 127.0.0.1:8000/helloworld.
URL () function: Can receive four parameters, which are two required parameters regex, view and two optional parameters Kwargs, name:
①regex: Regular expression, the URL that matches it executes the corresponding second parameter view.
②view: Used to perform a URL request that matches a regular expression.
③kwargs: The parameter of the dictionary type used by the view.
④name: Used to reverse get the URL.
6. Django Template
1) Example:
① in the app directory, create the Templates directory and build the helloworld.html file:
-
② the path to the Django description template file, modify the settings.py file, modify the DIRS in TEMPLATES to [base_dir+ "/templates"].
③ Modifying views.py:
From django.shortcuts Import Render
def hello (Request):
context = {}
context[' helloWorld ' = ' Hello world! '
return render (Request, ' helloworld.html ', context)
Render uses a dictionary context as a parameter, and the key value "HelloWorld" of the element in the context dictionary corresponds to the variable "{{HelloWorld}}" in the template.
④ start the server and access it in the browser: 127.0.0.1:8000/helloworld.
2) Django template tag
①if/else Label
If/else supports nesting, {% if%} tags accept and, or or not keywords to make judgments on multiple variables, or to negate variables.
- {% if condition%}
- ...
- {% ENDIF%}
Or:
- {% if condition1%}
- ...
- {% elif Condiiton2%}
- ...
- {% Else%}
- ...
- {% ENDIF%}
②for Label
{% for%} allows iterations on a sequence. Nesting is supported. In each iteration, the template system renders all content between {% for%} and {% endfor%}.
- <ul>
- {% for WHO in list%}
- <li>{{Person.name}}</li>
- {% ENDFOR%}
- </ul>
Adding a reversed to the label causes the list to be reversed:
- {% for WHO in list%}
- ...
- {% ENDFOR%}
③ifequal/ifnotequal Label
The {% ifequal%} label compares two values and displays all values in {% ifequal%} and {% endifequal%} when they are equal. Similar to {% if%}, {% ifequal%} supports optional {% else%} tags.
- {% ifequal person1 person2%}
-
- {% endifequal%}
④ Comment Label
The Django comment uses {# #}.
⑤ Filter
The template filter can modify the variable before it is displayed, and the filter uses the pipe character:
{{Name|lower}} uppercase is converted to lowercase.
The output of one filter pipeline can also be used as input to the next pipe:
{{Name|first|upper}} converts the first element to uppercase.
Some filters have parameters, and the parameters of the filter follow the colon and are always enclosed in double quotes:
{{name|truncatewords: ' 3 '}} shows the first 3 words of a variable.
Addslashes: Adds a backslash to any backslash, single quotation mark, or double quotation mark before.
Date: Formats a date or DateTime object by the specified format string parameter, such as {{pub_date|date: "F J, Y"}}.
Length: Returns the lengths of the variables.
⑥include Label
The {% include%} tag allows the contents of other templates to be included in the template.
- {% include "test.html"%}
7. Django Model
Django provides good support for a variety of databases, and Django provides a unified call API for databases that can be selected according to business requirements.
Take MySQL database as an example, install the MySQL driver command: sudo pip install mysqlclient.
1) Database Configuration
Locate the DATABASES configuration item in the project's settings.py file and modify its information to:
DATABASES = {
' Default ': {
' ENGINE ': ' Django.db.backends.mysql ', # or use Mysql.connector.django
' NAME ': ' Test ',
' USER ': ' Test ',
' PASSWORD ': ' test123 ',
' HOST ': ' localhost ',
' PORT ': ' 3306 ',
}
}
The Chinese comment is added here, so we need to add #-*-Coding:utf-8-*-to the settings.py file header.
2) Defining the model
① Create app:
Django rules that if you want to use a model, you must create an app that uses the following command to create a App:python manage.py Startapp Testmodel.
② Modify the testmodel/models.py file:
From django.db import Models
Class Test (models. Model):
Name = models. Charfield (MAX_LENGTH=20)
The class name represents the database table name and inherits the models. Model, the field inside the class represents the field (name) in the data table, the data type is Charfield (equivalent to varchar), Datefield (equivalent to DateTime), and the max_length parameter limits the length.
③ found the Installed_apps in settings.py, adding: ' Testmodel '.
④ run the following command on the command line to create the data table with the name of the application name _ class name (for example: testmodel_test):
View Plain Copy
Python manage.py Migrate # CREATE TABLE structure
Python manage.py makemigrations Testmodel # Let Django know that the model has some changes
Python manage.py migrate Testmodel # CREATE TABLE structure
3) Database Operations
To add a database.py file:
[Python] View plain copy
From django.http import HttpResponse
From Testmodel.models import Test
def database (Request):
Test = Test (name= ' Alice ')
Test.save ()
Return HttpResponse ("<p> data added successfully! </p> ")
Modify urls.py:
View Plain Copy
From django.conf.urls Import *
From. Import View,database
Urlpatterns = [
URL (r ' ^hello$ ', View.hello),
URL (r ' ^database$ ', database.database)
]
Start the server and access it in the browser: 127.0.0.1:8000/database.
① Adding data
[Python] View plain copy
From django.http import HttpResponse
From Testmodel.models import Test
def database (Request):
Test = Test (name= ' Alice ')
Test.save ()
Return HttpResponse ("<p> data added successfully! </p> ")
② Getting Data
[Python] View plain copy
From django.http import HttpResponse
From Testmodel.models import Test
def database (Request):
# initialization
Response = ""
Response1 = ""
# All data rows are obtained by objects all () of this model manager, equivalent to the SELECT * from in SQL
List = Test.objects.all ()
# filter is equivalent to where in SQL to set conditional filter results
Response2 = Test.objects.filter (id=1)
# Get a single object
RESPONSE3 = Test.objects.get (id=1)
# Limit the returned data, equivalent to the offset 0 limit 2 in SQL;
Test.objects.order_by (' name ') [0:2]
# Data sorting
Test.objects.order_by ("id")
# The above method can be used in chain
Test.objects.filter (name= "Alice"). Order_by ("id")
# Output All data
For Var in list:
Response1 + = Var.name + ""
Response = Response1
Return HttpResponse ("<p>" + response + "</p>")
③ Updating data
[Python] View plain copy
From django.http import HttpResponse
From Testmodel.models import Test
def database (Request):
# Modify the Name field of Id=1 and save, equivalent to the update in SQL
Test = Test.objects.get (id=1)
Test.name= ' Alice '
Test.save ()
# Another way
# Test.objects.filter (id=1). Update (name= ' Alice)
# Modify all the columns
# Test.objects.all (). Update (name= ' Google ')
Return HttpResponse ("<p> Data modification Success </p>")
④ Deleting data
Deleting an object in a database simply calls the object's Delete () method:
[Python] View plain copy
From django.http import HttpResponse
From Testmodel.models import Test
def database (Request):
# Delete Id=1 's data
Test = Test.objects.get (id=1)
Test.delete ()
# Another way
# Test.objects.filter (id=1). Delete ()
# Delete all data
# Test.objects.all (). Delete ()
Return HttpResponse ("<p> Data deletion success </p>")
8. Django Form
1) Get method
① Create a search.py file to receive the user's request:
[Python] View plain copy
From django.http import HttpResponse
From django.shortcuts import Render_to_response
# Forms
def search_form (Request):
Return Render_to_response (' search_form.html ')
# Receive Request data
def search (Request):
request.encoding= ' Utf-8 '
If ' Q ' in Request. GET:
Message = ' Search for content: ' + request. get[' Q '].encode (' utf-8 ')
Else
Message = ' An empty form was submitted '
return HttpResponse (Message)
② add search_form.html form in templates:
[HTML] View plain copy
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title></title>
<body>
<form action= "/search" method= "Get" >
<input type= "text" name= "Q" >
<input type= "Submit" value= "Search" >
</form>
</body>
③ Modifying urls.py:
[Python] View plain copy
From Django.conf.urls import URL
From. Import View,database,search
Urlpatterns = [
URL (r ' ^helloworld$ ', View.helloworld),
URL (r ' ^database$ ', database.database),
URL (r ' ^search-form$ ', search.search_form),
URL (r ' ^search$ ', Search.search)
]
④ start the server and access it in the browser: 127.0.0.1:8000/search_form.
2) Post method
① add post.html form in templates:
[Python] View plain copy
<! DOCTYPE html>
<meta charset= "Utf-8" >
<title></title>
<body>
<form action= "/search-post" method= "POST" >
{% Csrf_token%}
<input type= "text" name= "Q" >
<input type= "Submit" value= "Search" >
</form>
<p>{{RLT}}</p>
</body>
{% Csrf_token%} tags: csrf full name is the cross Site request forgery, which is the functionality Django provides to prevent spoofing submission requests. The POST method submits a table that must have this label.
② Create a new search2.py file and use the Search_post function to process the POST request:
[Python] View plain copy
From django.shortcuts Import Render
From django.views.decorators import csrf
# Receive POST request data
def search_post (Request):
CTX ={}
If request. POST:
ctx[' RLT ' = Request. post[' Q ']
return render (Request, "post.html", CTX)
③ Modifying urls.py:
[Python] View plain copy
From Django.conf.urls import URL
From. Import View,database,search
Urlpatterns = [
URL (r ' ^helloworld$ ', View.helloworld),
URL (r ' ^database$ ', database.database),
URL (r ' ^search-form$ ', search.search_form),
URL (r ' ^search$ ', Search.search)
URL (r ' ^search-post$ ', search2.search_post)
]
④ start the server and access it in the browser: 127.0.0.1:8000/search_post.
Django is one of the hottest frameworks for Python development! Little White must learn the Django framework!