Django "17th" uses form components and AJAX to implement user registration

Source: Internet
Author: User

First, registration-related knowledge points

1. Form Components

We generally write the form when it is written in the views view, then he and our view function does not affect, we can it separate out, under the application of a forms.py file to store

2. Local hook function

def clean_username (self):        username = self.cleaned_data.get ("username")        valid = models. UserInfo.objects.filter (username = username). First ()        if valid:            raise ValidationError ("User name already exists")        return Username

3. Global hook function

#自定义全局钩子: Verify that two times the password is the same as Def clean:   if Self.cleaned_data.get ("password") = = Self.cleaned_data.get ("Password_ Again "):        return self.cleaned_data   else:        raise  validationerror (" Two times password Inconsistent ")

4. jquery Property Operations Related

attr:    One parameter is to get the value of the property, and two parameters is to set the property value Removeattr (property name):    Delete the property value prop: The    return value of the property is the Boolean type (select, reverse, cancel example) Removeporp:    Delete the value of an attribute

5, the cycle of two ways:

$.each (Array/object, function (i,v) {})
$ ("div"). each (function (i,v) {})

6, three kinds of hiding in CSS:

1, Display:none  Hide All content
2, Visibility:hidden hidden content 3, Overflow:hidden hidden overflow content Three are used to hide: The difference is: visibility although hidden, but the hidden content still occupy this space, This hidden content space will appear blank in the Web page.
and display: Hide the non-occupy space we do not have to display:none when registering, otherwise choose the file of that function will not have, we can transparency

7. Submit binary Data with Formdata


Formdata.append ("Email", $ ("#id_email"). Val ()); Formdata.append ("Tel", $ ("#id_tel"). Val ());
Formdata.append ("Password", $ ("#id_password"). Val ()); Formdata.append ("Password_again", $ ("#id_password_again"). Val ()); Formdata.append ("Avatar_img", $ ("#avatar") [0].files[0]);

Remember to add

ContentType:falseprocessData:false

8, you can use the following method to determine what is the request

If Request.ajax ():    #如果ajax请求if request,method== "POST":   #如果是POST请求

9, upload the file has a fixed configuration parameters media, and static similar but different

The steps are as follows:

-First configured in Settings:

# ============media configuration ===============media_url= "/media/"  #别名MEDIA_ROOT =os.path.join (Base_dir, "App01", "MEDIA" , "uploads")   #具体路径

-Configure in URL

URL (r ' ^media/(? p<path>.*) $ ', serve, {' Document_root ': Settings. Media_root}),

Use:

Use one:
-----
Useful two:
------

If the upload is successful, the image will be saved here automatically.

10. Portrait Picture Preview

   Avatar Preview        $ (". Avatar_file"). Change (function () {            var ele_file = $ (this) [0].files[0];//Current selected file            var reader = New FileReader ();            Reader.readasdataurl (Ele_file); correspond to find open URL            reader.onload=function () {{# #                way One #}                $ (". Avatar_img"). attr ("src", this.result);// This.result is found above url{#                way two #}{#                 $ (". Avatar_img") [0].src=this.result;//Set Picture property #}}        )

11, the form automatically generated error message

When you define a global hook, and it happens to be the fault of your global hook function (such as two times the password input is inconsistent), so that when you print the error message

There will be a __all__ object, which is generated by the global hooks you set.

So you have to judge alone, now there is only one global hook, you can judge, but when the global hooks have to be a separate to judge

  if (i== "__all__") {        $ ("#id_password_again"). After ($span)   }

Second, the specific implementation of registration operations

urls.py

From django.conf.urls import urlfrom django.contrib import adminfrom app01 import viewsfrom django.conf import Settingsfro M django.views.static Import serveurlpatterns = [    url (R ' ^admin/', admin.site.urls),    url (r ' ^login/$ ', views.login),    url (r ' ^index/$ ', views.index),    url (r ' ^get_vaildcode_img/$ ', views.get_vaildcode_img)    , URL (r ' ^log_out/$ ', views.log_out), url (r '    ^register/$ ', views.register), url (r '    ^media/(? p<path>.*) $ ', serve, {' Document_root ': Settings. Media_root}),]

  

views.py

def register (Request):    if request.method== "GET":        form = Registerform ()        return render (Request, " Register.html ", {" form ": Form})    else:        form = Registerform (data=request. POST)        regresponse = {"User": None, "Msg_errors": none}        if Form.is_valid ():            username = form.cleaned_ Data.get ("username")            password = form.cleaned_data.get ("password")            tel = form.cleaned_data.get ("tel")            avatar_img = Request. Files.get ("avatar_img")            print (">>>", Username,password,tel)            models. UserInfo.objects.create_user (username = username,password=password,tel=tel,avatar=avatar_img)            regresponse[" User "] = Username        else:            print (" Form.errors ", form.errors)            regresponse[" Msg_errors "]=form.errors        return HttpResponse (Json.dumps (regresponse))

  

forms.py

#!usr/bin/env python#-*-coding:utf-8-*-from app01 import modelsfrom django.forms import formfrom django.forms import WI Dgetsfrom django.forms Import fieldsfrom django.core.validators import Validationerrorfrom django.core.validators Import Regexvalidatorclass Registerform (Form): username = fields.  Charfield (Required=true, max_length=16, min_length=3, error_messages={"required": "User name cannot be empty", "max_length": "Length cannot be greater than", "min_length": "Length cannot be less than 3",}, Widget=widgets. TextInput ({"placeholder": "Please enter user name", "Class": "Form-control"})) Password = fields.  Charfield (Required=true, max_length=16, min_length=3, error_messages={"required": "Password cannot be empty", "max_length": "Length cannot be greater than", "min_length": "Length cannot be less than 3",}, Widget=widgets. Passwordinput ({"placeholder": "Please enter a password for the combination of numbers and letters", "Class": "Form-control"})) Password_again = fields. Charfield (Required=truE, max_length=16, min_length=3, error_messages={"required": "Password cannot be empty", "Max_len Gth ":" Length can not be greater than 3 "," min_length ":" Length can not be less than ",}, Widget=widgets. Passwordinput ({"placeholder": "Please enter your password again", "Class": "Form-control"})) email = fields.        Emailfield (Required=true, error_messages={"required": "Mailbox cannot be empty", "Invalid": "Mailbox format is incorrect" }, Widget = Widgets. EmailInput ({"placeholder": "Please enter your mailbox", "Class": "Form-control"})) Tel = fields. Charfield (Required=true, max_length=11, min_length=11, error_messages={"required" : "Mobile phone number cannot be empty", "max_length": "Length must be 11 bits, please enter correctly", "min_length": "Length must be 11 bits, please enter correctly", ",", Valida Tors=[regexvalidator ("\d+", "Password can only be number")], widget=widgets.         TextInput ({"placeholder": "Please enter your phone, request 11-bit Oh", "Class": "Form-control"}) #自定义用户名验证: Local hook def clean_username (self): Username = Self.cleaned_daTa.get ("username") valid = models. UserInfo.objects.filter (username = username). First () If Valid:raise validationerror ("User name already exists") re Turn username #自定义密码验证: def clean_password (self): password = self.cleaned_data.get ("password") if pass Word.isdigit (): Raise ValidationError ("Password cannot be a pure number") Else:return password #自定义全局钩子: Verify that two times the password is one def clean (self): if Self.cleaned_data.get ("password") = = Self.cleaned_data.get ("Password_again"): R Eturn self.cleaned_data else:raise validationerror ("Two times password Inconsistent")

  

Template

Register.html
<! DOCTYPE html>

  

Reg.css
. c1 {    margin-right:10px;} h2 {    margin-top:100px;    margin-left:280px;}. left{    position:relative;}. right{    width:270px;    height:294px;    Position:absolute;    top:197px;    left:886px;}. registr_btn{    width:100px;    margin-left:200px;}. avatar{    position:relative;    width:70px;    height:70px;}. avatar_img,.avatar_file{    Position:absolute;    width:70px;    height:70px;    top:0;    left:46px;}. avatar_file{    opacity:0;}

  

Effect

Django "17th" uses form components and AJAX to implement user registration

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.