In the previous section, we completed the background management of the member function. In this section, we need to complete the Member registration function, involving the following modules:
- URL Configuration
- Views Module
- Template
- Use of request/response object
Project address: https://gitee.com/ccnv07/django_example
URL routing configuration
Django defines the URL routing of a website through the project's URLs. py file, which is the CMS/URLs. py file in our project.
Basic Django access process
- When accessing a URL, you can use the URL route defined in CMS/URLs. py to obtain the view function or class to be executed (stored in views. py)
- Forward the request (request object) to the specified view function/class and execute the view function/class code.
- Use the template rendering (other resource objects such as jsonresponse if no template is available) to return the result data and output it to the browser.
Open the CMS/URLs. py file
from django.contrib import adminfrom django.urls import pathurlpatterns = [ path(‘admin/‘, admin.site.urls),]
Urlpatterns is a list of the entire route and is a fixed name defined by Django.
Path Function
PATH (route, view, kwargs = none, name = none)
route
: Route entry for access
view
: View functions/classes for access
name
: Specifies the name of this route. With this name, we can generate an accessible URL.
By default, this route defines the access URL of the entire backend, all starting with admin/. Django will load all the routes defined in Admin. Site. URLs.
For example, the URL of the background management function is:/admin/account/account/
Routing route parameter format 1. Fixed string Routing
This route is a fixed access URL and will not change, for example, about my access page.
urlpatterns = [ path(‘about/‘, views.about),]
2. url routing with variables, such as accessing articles in a specified topic
urlpatterns = [ path(‘list/<int:nav_id>‘, views.list),]
There should be more such use. <INT:> specify that this nav_id must be of the numeric type, and perform type forced conversion. nav_id is the parameter name, in the following way, you can access this parameter.
# views.pydef list(request, nav_id): pass
In addition to int, Django URL routing also supports four types: Str, slug, UUID, and path. Generally, STR and INT are commonly used.
3. Regular Expression Routing
from django.urls import path, re_pathfrom . import viewsurlpatterns = [ path(‘articles/2003/‘, views.special_case_2003), re_path(r‘^articles/(?P<year>[0-9]{4})/$‘, views.year_archive),]
The path function defines a common route.
Re_path Han du defines a regular route with identical Parameters
Like the re_path in the above example, each () is a parameter definition ,? P indicates that a parameter is defined here. <year> is the key parameter, and [0-9] {4} is a regular expression. The $ symbol indicates that the route ends and no matching is performed.
Therefore, this URL can match the URL such as articles/2018 /.
urlpatterns = [ re_path(r‘^comments/(?:page-(?P<page_number>\d+)/)?$‘, comments), # good]
In this example ,? : Indicates that this is a string URL, and page-is not a parameter
Therefore, the matched URL is the URL of comments/page-1.
4. Include other routes
from django.urls import include, pathurlpatterns = [ path(‘account/‘, include(‘account.urls‘)),]
Include
Include (module, namespace = none)
Include (pattern_list)
Include (pattern_list, app_namespace), namespace = none)
module
: Urlconf Module
namespace
: URL entry namespace
pattern_list
: Iteratable path ()/re_path instance class
app_namespace
: Namespace of the app at the url entry
We will talk about it in sequence.include(‘account.urls‘))
In this way, all URL routes defined in account/URLs. py are loaded
Here is the route defined in account/URLs. py.
# account/urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [ path(‘index/‘, views.index, name=‘account-index‘)]
According to the above routing rules, the URL we can access isaccount/index/
This URL
Define a route for Member registration to load module routing files into the project
# cms/urls.pyimport debug_toolbarfrom django.contrib import adminfrom django.urls import path, includeurlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘account/‘, include(‘account.urls‘))]
In this way, we can define the URL routing of the member module in the account/URLs. py file.
Define URL routing in the module
Create an account/URLs. py file
# account/urls.pyfrom django.urls import pathfrom . import viewsurlpatterns = [ path(‘register/‘, views.register, name=‘account-register‘)]
View module view Function Definition
from django.http import HttpResponseimport datetimedef current_datetime(request): now = datetime.datetime.now() html = "
Each view function has a fixed request parameter, which is a request object that contains parameters in the browser request, including common URLs, post data, request types, header headers, and so on.
Then, the returned view function must be a reponse object. Generally, we return HTML code, so we use the httpresponse object.
Sometimes we write interfaces and use jsonresponse objects.
The most common functions in the View: render template rendering Function However, if you write the HTML code in a python file, you can use the render function to render the template.
Render (request, template_name, context = none, content_type = none, status = none, using = none)
request
: Is the request object,
template_name
: Template File Name
context
: Variables to be passed to the template file
content_type
: Content-Type type in the header of the document
status
: HTTP response code, that is, 200,301,302,400,500
using
: Template engine to be used
from django.shortcuts import renderdef my_view(request): # View code here... return render(request, ‘myapp/index.html‘, { ‘foo‘: ‘bar‘, }, content_type=‘application/xhtml+xml‘)
Render automatically converts the object to an httpresponse object, so you do not need to write httpresponse again.
Redirect jump function When the Member registration is complete, we need to automatically jump to the member center page or the homepage, then we have to use the Redirect function to implement
Redirect (to, permanent = false, * ARGs, ** kwargs)
to
: The address to jump,
permanent
: Whether to jump permanently. To put it bluntly, it is the difference between code 301/302 and Baidu 301,302.
from django.shortcuts import redirectdef my_view(request): ... return redirect(‘/some/url/‘)
Reverse URL routing-to-URL Function When redirect completes the URL jump, if all the URLs I have defined have changed, I think the previously defined URLs are too ugly, too long, and the boss does not like them, isn't it so boring? Why can't I search for URLs for full projects?
In fact, Django has already thought of this. Remember what we did when we defined a URL route.name
Parameters?
By using the reverse function, you can convert the URL routing defined in URLs. py to a URL.
Reverse (viewname, urlconf = none, argS = none, kwargs = none, current_app = none)
viewname
: URL route name
urlconf
: URL routing module name. The default value is the root module, which is the URL. py in our CMS file.
args
: Parameters to be passed to URL Routing
Request and response objects in the view Generally, there are two types of resources after a request. One is the requested resource, which is the resource sent to the server by the browser, including the requested URL, header, passed parameter, cookie, and so on.
Another type is the returned resource, that is, the resource sent by the server to the browser.
Httprequest object Common attributes are as follows:
Attribute |
Description |
Scheme |
HTTP or HTTPS |
Body |
Request body |
Path |
Request Path account/register/ |
Path_info |
Request Path |
Method |
Request Method get, post |
Encoding |
Encoding type |
Content_type |
Content-Type of the header |
Cookies |
Cookie Information |
Files |
File Information uploaded by the file field of the form |
Meta |
Header information |
Session |
Save session information, dict Structure |
Common Methods
Method |
Description |
Get_host () |
127.0.0.1: 8000 |
Get_port () |
Request Port |
Get_full_path () |
Full Request Path |
Is_ajax () |
Ajax request? |
Httpresponse object Common attributes
Attribute |
Description |
Content |
Resource content returned by the request |
Charset |
Encoding |
Status_code |
Returned HTTP status code |
Jsonresponse object Jsonresponse (data, encoder = djangojsonencoder, safe = true, json_dumps_params = none, ** kwargs)
data
: JSON data to be returned, which is a dict Structure
encoder
: Data transcoding class, which generally does not need to be changed
json_dumps_params
: Json_dumps Function
For our project, we can define a common function to return jsonresponse in the CMS/utils. py (created if no one exists) file,
from django.http import JsonResponsedef return_json(code = 0, message = ‘success‘, data = [], url=‘‘): return JsonResponse({ ‘code‘: code, ‘url‘: url, ‘message‘: message, })
Template layer description template file path The default template file path will be in the module name/templates, but in normal project development, all templates will be put together, so we need to redefine the template path
# CMS/settings. pytemplates = [{'backend': 'django. template. backends. django. djangotemplates ', 'dirs': [# Place the templates directory in the root directory OS. path. join (base_dir, 'templates'),], 'app _ dirs': True, 'options': {'Context _ processors ': ['django. template. context_processors.debug', 'django. template. context_processors.request ', 'django. contrib. auth. context_processors.auth ', 'django. contrib. messages. context_processors.messages ',] ,},},]
In settings. py, add OS. Path. Join (base_dir, 'templates') to templates. dirs, and change the directory of the template file to CMS/templates.
Modify static resource file paths and access URLs The static file path is the same as the template path. We also need to modify it to the root directory.
# cms/settings.pySTATIC_URL = ‘/static/‘STATICFILES_DIRS = (‘static‘, )
Common Template labels Generally, the top and bottom of a template are the same in many places, so we can define a layout HTML page and extract the same places and put them together.
# templates/layout.html{% load static %}<!DOCTYPE html>
load static
This label is used to load the static module. You can use {% static %} to read static resource files only after loading.
block endblock
Define different blocks and name each block.
This assumes that I have defined a Member registration page.
# Templates/account/register.html {% extends 'layout.html '%} {% block title %} register {% endblock %}
Then {% block title %} {% endblock %} In layout.html will be replaced with "register"
extends
Tag: the custom Layout layout.html.
Define a registered member form We first define the form registerform in account/forms. py. Because a accountform has been defined before, this form can directly inherit the accountform
Class registerform (accountform): # The setting scenario is to add the user scene = 'insert' class Meta (accountform. meta): # when using a custom form, you must specify the fields or exclude attribute. Otherwise, an error is reported. # when registering a form, we do not need to set the status and field, so we can exclude it. Fields = ('account', 'Password', 'email ', 'phone ')
During registration, you usually need to enter a duplicate password. Therefore, we need to define a rep_password field.
Class registerform (accountform ):... ignore the code rep_password = forms. charfield (Label = 'Repeat password', required = true, error_messages = {'requestred': 'enter password' again}, widget = forms. passwordinput () def clean_rep_password (Self): # verify whether the two passwords are consistent # because the clean_password method has encrypted cleaned_data ['Password'], therefore, only data ['Password'] If self can be obtained here. data ['Password']! = Self. cleaned_data ['rep _ password']: Raise validationerror ('inconsistent passwords entered twice ') return self. cleaned_data ['rep _ password']
Define View In the view, if it is a GET request, we will render the form. If it is a POST request, we will execute the registered user
GET Request Code
from django.shortcuts import renderfrom .forms import RegisterFormdef register(request): form = RegisterForm() return render(request, ‘account/register.html‘, {‘form‘: form})
Compile template code I am using the bootstrap front-end framework. You can download it and put it in the static folder to correct the path in layout.html.
First, we first load the layout.html layout template.
# Templates/account/register.html {% extends 'layout.html '%} {% block title %} register {% endblock %}
Then, in the block body section, write the form to be rendered.
{% Block body %} <Div class = "Container"> <Div class = "row" style = "width: 500px "> <form action =" {% URL 'account-register '%} "method =" Post "onsubmit =" return post (this) ">{% csrf_token %} <Div class =" form-group "> <label for =" {form. account. id_for_label }}" >{{ form. account. label }}</label >{{ form. account }}</div> <Div class = "form-group"> <label for = "{form. password. id_for_label }}" >{{ form. password. label }}</label >{{ form. password }}</div> <Div class = "form-group"> <label for = "{form. rep_password.id_for_label} ">{{ form. rep_password.label }}</label> {form. rep_password }}</div> <Div class = "form-group"> <label for = "{form. email. id_for_label }}" >{{ form. email. label }}</label >{{ form. email }}</div> <Div class = "form-group"> <label for = "{form. phone. id_for_label }}" >{{ form. phone. label }}</label >{{ form. phone }}</div> <input type = "Submit" value = "Submit" class = "BTN-success"> </form> </div> {% endblock %}
In most cases, the same is true. The form in {form.} is the Form class we passed in the view.
form.account_id_for_label
: Indicates the input class.
{{ form.account.label}}
: Is the name of the displayed form field
{{ form.account}}
: A piece of input form field code is generated directly.
Open the browser and we can see the effect.
Looks good
Now, we can click Submit to try it out.
5. Use django2.0 to implement the Member registration function