Django Each application of the framework can have its own templates urls.py static Folder , Based on this feature ,Django Be able to do group development very well ( That is, everyone only writes his own app)
And finally by boss take app Copy all to a new Django In the project Then register all in the configuration file app, At last, we use the characteristics of routing method to divide all app integrated
When one Django In the project url Especially many times Total route urls.py The code is very redundant and difficult to maintain , At this time, routing distribution can also be used to reduce the pressure of total routing
After using the total route distribution The master route is no longer the direct correspondence between the route and the view function, but a distribution process
Identify the current url It belongs to that application Directly distribute to the corresponding application for processing
usage :
# The total route is imported into each app Middle road by and module
from django.conf.urls import url, include
from app01 import urls as app01_urls
from app02 import urls as app02_urls
urlpatterns = [
url(r'^admin/', admin.site.urls),
# 1. Route distribution mode 1
url(r'^app01/',include(app01_urls)), # as long as url The prefix is app01 start Give it all to app01 Handle
url(r'^app02/',include(app02_urls)) # as long as url The prefix is app02 start Give it all to app02 Handle
# 2. Route distribution mode 2( recommend ) No aliasing
url(r'^app01/',include('app01.urls'))
url(r'^app02/',include('app02.urls'))
# From the middle of the road
# app01 urls.py
from django.conf.urls import url
from app01 import views
urlpatterns = [
url(r'^reg/',views.reg)
]
# app02 urls.py
from django.conf.urls import url
from app02 import views
urlpatterns = [
url(r'^reg/',views.reg)
]
Be careful :
In the general route url Never add $ End of character
resolvent :
1. The name space
# Total route
url(r'^app01/',include('app01.urls',namespace='app01')),
url(r'^app02/',include('app02.urls',namespace='app02'))
# When parsing
app01:
urlpatterns = [
url(r'^reg/',views.reg,name='reg')
]
app02:
urlpatterns = [
url(r'^reg/',views.reg,name='reg')
]
reverse('app01:reg')
reverse('app02:reg')
front end :
{
% url 'app01:reg' %}
{
% url 'app02:reg' %}
# But as long as the names don't conflict There is no need to use namespaces
2. There are many. app When , Add... When aliasing app The prefix of , In this way, multiple app Names do not conflict
app01:
urlpatterns = [
url(r'^reg/',views.reg,name='app01_reg')
]
app02:
urlpatterns = [
url(r'^reg/',views.reg,name='app02_reg')
]
Pseudo static refers to the disguise of a dynamic web page as a static web page
Static web page : The data is dead Will not be the edge of the web page
The role of pseudo static :
- The purpose of pseudo static is to increase the seo Query strength and increase the probability that search engines collect this website
summary :
- No matter how you optimize it How to deal with Can't do anything RMB The player
Role of virtual environment :
When you do not create a virtual environment, it is similar to downloading a pure python Interpreter
notes : Don't create too many virtual environments , It will consume hard disk space
Expand :
- During development, we will equip each project with a requirements.txt file , It contains all modules and versions of the project
- You just need to enter pip install (-r) requirements.txt Command to install all modules in the file
- Generate requirements.txt File command : pip freeze > requirements.txt
pycharm Creating a virtual environment
Django 1.x The middle road is used by the floor url Method , And in the Django2.x and 3.x The routing layer in the version uses path Method
url() The first parameter supports regular
path() The first parameter doesn't support regular Match what you write
Of course, there are corresponding methods to use regularization :
# Recommended re_path
from django.urls import path, re_path
from django.conf.urls import url
re_path(r'^index/',index)
url(r'^login/',login)
stay 2.x and 3.x Inside re_path It is equivalent to 1.x Inside url
- although path Regular... Is not supported But it internally supports five types of converters
# First convert the contents of the second route into integers, and then pass them to the following view functions in the form of keywords
path('index/<int:id>/',index)
str : Matches except for the path separator (/) A non - empty string , This is the default form
int : Matching positive integer , contain 0.
slug : Match the letter 、 Numbers and bars 、 String of underscores .
uuid : Match formatted uuid, Such as 075194d3-6885-417e-a8a8-6c931e272f00.
path : Match any non empty string , Contains the path separator (/)( Out-of-service ?)
- In addition to the five default Converters Custom converters are also supported ( understand )
1. app So let's make a new one .py File is written to
class MonthConverter:
regex='\d{2}' # The property name must be regex
def to_python(self, value):
return int(value)
def to_url(self, value):
return value # Matching regex It's two numbers , The result returned must also be two numbers
2. urls.py in
from django.urls import path,register_converter
from app01.path_converts import MonthConverter
# Register the converter first
register_converter(MonthConverter,'mon')
from app01 import views
urlpatterns = [
path('articles/<int:year>/<mon:month>/<slug:other>/', views.article_detail, name='aaa'),
]
3. views.py View functions in
from django.shortcuts import render,HttpResponse,reverse
def article_detail(request,year,month,other):
print(year,type(year))
print(month,type(month))
print(other,type(other))
print(reverse('xxx',args=(1988,12,'hello'))) # Reverse parsing results /articles/1988/12/hello/
return HttpResponse('xxxx')
- Inside the model layer 1.x Foreign keys are deleted by cascading updates by default , But in 2.x and 3.x You need to manually configure parameters in
models.ForeignKey(to='Publish',on_delete=models.CASCADE,on_update=models.VASCADE)
""" HttpResponse Return string type render return html page And before returning to the browser, you can also give html File transfer value redirect Redirect """
Be careful : The view function must return a HttpResponse object You can see from the source code ,render and redirect All inherited HttpResponse
render Simple internal principles :
def myrender(request):
from django.template import Template,Context
res = Template('<h1>{
{ user }}</h1>')
con = Context({
'user':{
'username':'jason','password':123}})
ret = res.render(con)
print(ret)
return HttpResponse(ret)
''' json Format data , It can realize cross language data transmission between front end and back end Front end serialization JSON.stringify() Corresponding json.dumps() JSON.prase() Corresponding json.loads() '''
Return the string to the front end
import json
from django.http import JsonResponse
def ab_json(request):
user_dict = {
'username':'jason So handsome , I love !','password':'123','hobby':'girl'}
l = [111,222,333,444,555]
# 1. The way 1
# Turn into json Format string
json_str = json.dumps(user_dict,ensure_ascii=False)
# Returns the string to
return HttpResponse(json_str)
# 2. The way 2
# Read the source code and master the usage
return JsonResponse(user_dict,json_dumps_params={
'ensure_ascii':False})
Be careful :
# JsonResponse By default, only dictionaries can be serialized Serialization of others requires addition of safe Parameters
return JsonResponse(l,safe=False)
''' form When uploading file type data from a form, you should pay attention to the following two points 1. method Must be designated as post 2. enctype It must be replaced by formadta '''
The front-end code
<form action="" method="post" enctype="multipart/form-data">
<p>username: <input type="text" name="username"></p>
<p>file:<input type="file" name="file"></p>
<input type="submit" value=" Submit ">
</form>
views.py
def ab_file(request):
if request.method == 'POST':
print(request.POST)
print(request.FILES) # Get file data
file_obj = request.FILES.get('file') # Get file object
with open(file_obj.name,'wb') as f:
for line in file_obj.chunks(): # It is recommended to add chunks Method In fact, it is the same as not adding
f.write(line)
return render(request, 'form.html')
""" request.method request.POST request.GET request.FILES request.body # Binary data sent from native browsers I will talk about it in detail later request.path # Get complete url request.path_info # Get complete url request.get_full_path() Can get the complete url And parameters after the question mark """
print(request.path) # /app01/ab_file/
print(request.path_info) # /app01/ab_file/
print(request.get_full_path()) # /app01/ab_file/?username=jason
# The view function can be either a function or a class
def index(request):
return HttpResponse('index')
FBV
def index(request):
return HttpResponse('FBV')
CBV
# CBV route
url(r'^login/',views.MyLogin.as_view())
# views.py
from django.views import View
class MyLogin(View):
def get(self,request):
return render(request,'form.html')
def post(self,request):
return HttpResponse('post Method ')
""" FBV and CBV Each has its own merits ,request Formal parameters are essential CBV characteristic It can be directly matched to the corresponding method for execution according to different request methods """
Be careful : Do not modify the source code easily
adopt urls.py Routing distribution in
url(r'^login/',views.MyLogin.as_view())
''' Function name / Method name Bracketed execution has the highest priority '''
as_view() Main source code
@classonlymethod # Inherited classmethod Method Can only be called by class
def as_view(cls, **initkwargs):
''' as_view Decorated by class methods ,cls It's our own class '''
def view(request, *args, **kwargs):
self = cls(**initkwargs) # cls It's our own class
# self = MyLogin(**initkwargs) Generate an object of our own class
return self.dispatch(request, *args, **kwargs)
return view
''' as_view Method return value is view Method , here views.MyLogin.as_view() Equate to views.view At this time , We can find out view Method return value is self.dispatch(request, *args, **kwargs) '''
dispatch(request, *args, **kwargs) Main source code
# CBV The essence of
def dispatch(self, request, *args, **kwargs):
if request.method.lower() in self.http_method_names:
handler = getattr(self, request.method.lower(), self.http_method_not_allowed)
""" Reflection : Manipulate the properties or methods of an object through a string handler = getattr( The object generated by the class written by yourself ,'get', When you can't find it get The third parameter will be used for attribute or method ) handler = We write our own classes get Method """
else:
handler = self.http_method_not_allowed
return handler(request, *args, **kwargs)
''' Automatically call get Method '''