3. Use django2.0 for development.

Source: Internet
Author: User
GitHub address: https://gitee.com/ccnv07/django_example

This chapter describes how to register and log on to the front-end of a member. The following modules are involved:

  1. Simple route settings
  2. Simple template operations
  3. View and session operations
  4. Complex forms
  5. Ajax requests and JSON returned Resources

Use the model in the previous section.

Implement registration
# Account/forms. pyclass accountform (forms. modelform ):#... ignore code def get_first_error (Self): # Get all errors converted to the JSON format errors = self. errors. get_json_data () If errors: for key, message_dicts in errors. items (): # returns the first error message if an error exists. Returns string return message_dicts [0]. get ('message') return none
Create a registry ticket

Registerform inherits accountform

# Account/forms. pyclass registerform (accountform): # The setting scenario is for new users. # this is not the default setting for Django. It is added by myself, it is used to implement different custom rules in different scenarios. Scene = 'insert' def _ init _ (self, * ARGs, ** kwargs): Super (). _ init _ (* ARGs, ** kwargs) # because the front-end framework uses Bootstrap, you need to add class names to all form elements # Similarly, you can also use self. field name. widget. attrs. update ({'html attribute name', 'html attribute name'}) for _ field in self. fields: Self. fields [_ field]. widget. attrs. update ({'class': 'form-C Ontrol '}) # because the password field set in the base class is optional, It is required during registration, so set the required attribute of password to true # At the same time, we do not need the Status field, so set it to false self. fields ['Password']. required = true self. fields ['status']. required = false class Meta (accountform. meta): # when using a custom form, you must specify the fields or exclude attribute. Otherwise, an error is reported. # only specify the field fields = ('account', 'Password ', 'email ', 'phone') # Add a rep_password field to allow the user to enter the password twice to prevent the error rep_password = forms. charfield (Label = 'repeated 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']
Create a route entry registered by the user module

Create a URLs. py file in the account directory.
Then load the URLs. py file in the account in CMS. URLs.

From Django. contrib import adminfrom Django. URLs import path, includeurlpatterns = [path ('admin/', admin. site. URLs), # The include method parameter is the URL file loading address. You can specify the path ('account/', include ('account. URLs ')]

Create a logon route in account. URLs. py.

# Account/URLs. pyfrom Django. URLs import pathfrom. import viewsurlpatterns = [# The accessed URL path is http: // xxx/account/register # forward the request to the Register Method # The route name is account-register path ('register/', views. register, name = 'account-register '),]
Specific registration Logic

Basic Process:

  1. Put data in Form
  2. Verification Form
  3. Save the data in the form to the database
  4. The specified resource is returned for all successful and failed requests.
# Account/views. pyfrom Django. views. decorators. HTTP import require_http_methodsfrom. forms import registerformfrom CMS. utils import return_json # specify the Request Method @ require_http_methods (['get', 'post']) def register (request): If request. method = 'post': # Put all post data in the Form = registerform (request. post) # verify that the data in the form is correct if form. is_valid (): # Save the data to the database form. save () # after the operation succeeds, return the data to the browser return return_json (url = reverse ('account-Index') else: # verification failed, get the first error message from form and return it to the browser return return_json (code = 1, message = form. get_first_error () else: form = registerform () return render (request, 'account/register.html ', {'form': form })

A return_json method is added in this method. The Code is as follows:

# cms/utils.pyfrom django.http import JsonResponsedef return_json(code = 0, message = ‘success‘, data = [], url=‘‘):    return JsonResponse({        ‘code‘: code,        ‘url‘: url,        ‘message‘: message,    })

This code indicates returning a JSON resource to the browser for parsing.

Insert a template Configuration

The default template directory of Django is in module/templates.
For example, the template directory of the Account module is in account/templates
In general development, all templates are put together. Therefore, you need to modify the configuration file and specify the path of the template directory to the root directory.

# CMS/settings. pytemplates = [{'backend': 'django. template. backends. django. djangotemplates ', 'dirs': [# Put the templates directory in the root directory, that is, OS in CMS/templates. 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 addition, static resources (CSS, JS, fonts, IMG) files are generally stored in the root directory.
Or add the configuration in CMS/settings. py.

Static_url = '/static/' # specify the access URL prefix of the static file staticfiles_dirs = ('static ',) # specify the directory address of the static file

In this way, the new paths of the template and static resources become CMS/templates, CMS/static
The Style File uses Bootstrap. You can download it in advance and put it into the static file in advance.
Then the directory is changed to the following:

cms/    templates/    static/        css/        fonts/        js/
Create a registry ticket Template

Create a layout.html framework file in templates.
Layout.html contains the places shared by all templates and uses block label placeholders to hold space. Other templates can inherit layout.html, and then modify the content in the placeholder of the block label to greatly reduce the amount of code.

# Templates/layout.html <! -- Load the static template to use {% static 'filepath' %} to Load Static resources --> {% Load Static %} <! Doctype HTML> <HTML lang = "en"> 

Register the template file, templates/account/register.html

<! -- Inheritance layout.html -- >{% extends 'layout.html '%} <! -- Change the content in the placeholder name "title" to "register" --> {% block title %} register {% endblock %} {% block body %} <Div class = "Container"> <Div class = "row" style = "width: 500px "> <! -- URL 'route name, is the name '--> <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 %}

Key notes about form
Form. The field name is the access field
Form. Field name. id_for_label, which is the ID of the returned Field
Form. Field name. label, which is the label name
Form. The field name directly returns the html of the form element.
For example, form. Account is changed&lt;input type="password" name="password" maxlength="12" minlength="6" class="form-control" required id="id_password" /&gt;

Codereturn post(this)The JS Function Code of is as follows:

# Static/JS/utils. jsfunction post (form) {$. ajax ({URL: $ (form ). ATTR ('action'), method: 'post', datatype: 'json', data: $ (form ). serialize (), success: function (data) {If (data. code = 0) {layer. MSG ('Operation successful '); window. location. href = data. URL;} else {layer. MSG (data. message) ;}}) return false ;}
Start the development server and Test
python manager.py runserver

Logon Method

The login method is the same as the registration process. You can try to implement the following by yourself. If it is difficult, you can compare it with my code.

# Account/forms. pyclass loginform (accountform): Scene = 'login' def _ init _ (self, * ARGs, ** kwargs): Super (). _ init _ (* ARGs, ** kwargs) for _ field in self. fields: Self. fields [_ field]. widget. attrs. update ({'class': 'form-control'}) # Set password to mandatory self. fields ['Password']. required = true self. fields ['email ']. required = false self. fields ['phone']. required = false self. fields ['status']. required = false class Meta (accountform. meta): # If you use a custom form, you must specify the fields or exclude attribute. Otherwise, fields = ('account', 'Password') is returned ')
# Account/views. pyfrom Django. shortcuts import renderfrom Django. URLs import reversefrom Django. views. decorators. HTTP import require_http_methodsfrom Django. shortcuts import redirectfrom. forms import registerform, loginformfrom. utils import authenticate, login_requiredfrom CMS. utils import return_jsonfrom functools import wraps @ login_required (login_url = '/account/login/') def index (request): Return render (request, template_name = 'account/index.html ') @ require_http_methods (['get', 'post']) def login (request): If request. method = 'post': form = loginform (request. post) If form. is_valid (): User = authenticate (request, account = form. cleaned_data ['account'], password = form. cleaned_data ['Password']) If user is not none: Return return_json (url = reverse ('account-Index') else: Return return_json (code = 1, message = 'incorrect account or password ') else: Return return_json (code = 1, message = form. get_first_error () else: form = loginform () return render (request, 'account/login.html ', {'form': form })
# account/utils.pyfrom .models import Accountfrom django.contrib.auth.hashers import check_passwordfrom django.shortcuts import redirectfrom functools import wrapsdef authenticate(request, account, password):    try:        user = Account.objects.get(account=account)    except Account.DoesNotExist:        return None    if not check_password(password, user.password):        return None    request.session[‘user_id‘] = user.id    request.session[‘account‘] = user.password    return userdef login_required(func=None, login_url=‘‘):    def wrapper(func):        @wraps(func)        def _func(request, *arg, **kwargs):            if request.session.get(‘user_id‘):                return func(request, *arg, **kwargs)            else:                return redirect(login_url)        return _func    return wrapper

Request. session is a session object that can be used to save the user's information after logon. It is used in the same way as dict.

3. Use django2.0 for development.

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.