Form class creation
Using the form component requires that we create a class of our own
Import refrom Django Import formsfrom django.forms import widgetsfrom django.core.exceptions import Validationerrorfrom b Log import models# Create your views here.class RegForm (forms. Form): User = forms. Charfield (max_length=20, min_length=6, error_messages={"required": "User name cannot be empty", "Max_length": "User name cannot exceed 20 bits", "min_length": "User name cannot be less than 6 bits"}, widget=widgets. TextInput (attrs={"class": "Form-control"})) Nickname = Forms. Charfield (max_length=20, min_length=3, error_messages={"required": "User name cannot be empty", "Max_length": "User name cannot exceed 20 bits", "min_length": "User name cannot be less than 3 bits"}, widget=widgets. TextInput (attrs={"class": "Form-control"})) pwd = forms. Charfield (min_length=6, Widget=widgets. Passwordinput (attrs={"class": "Form-control"}), error_messages={"required": "Password cannot be empty", "min_l Ength ":" Password must not be less than 6 bits "}) repeat_pwd= Forms. Charfield (widget=widgets. Passwordinput (attrs={"class": "Form-control"}), error_messages={"required": "Confirm password cannot be empty"}) email = forms. Emailfield (error_messages={"Invalid": "Format Error", "Required": "Mailbox cannot be Empty"}, widget= Widgets. EmailInput (attrs={"class": "Form-control"})) Tel = forms. Integerfield (error_messages={"required": "Phone number cannot be empty"}, Widget=widgets. Numberinput (attrs={"class": "Form-control"}) def clean_user (self): User = Self.cleaned_data.get ("user") If models. UserInfo.objects.filter (Username=user). Exists (): Raise ValidationError ("User name already exists") Else:return User Def clean_nickname (self): nickname = Self.cleaned_data.get ("nickname") if models. UserInfo.objects.filter (Nickname=nickname). Exists (): Raise ValidationError ("nickname already exists") Else:ret URN Nickname def Clean_tel (self): Tel = self.cleaned_data.get ("tel") if Re.search ("^1[3458]\d{9}$", str (tel)): Return Tel el Se:raise ValidationError ("Phone number format error") def clean: pwd = self.cleaned_data.get ("pwd") Repea T_pwd = Self.cleaned_data.get ("repeat_pwd") if pwd = = Repeat_pwd:return Self.cleaned_data Else: Raise ValidationError ("Inconsistent password")
In this class we define the type of each field and some of the judging conditions.
Front-end Page rendering
{% load static%}<! DOCTYPE html>Instantiate an object from a class defined by the form component, using this object to render the front-end page
Avatar SelectionIn the front page we can see the option to have an avatar, in general, the user can click on the default frame of the avatar to choose their own image to upload
To achieve this, we first write a hidden input box (type=file), and then use the label tag to bind to him, to write the IMG tag inside the label tag
This will enable you to click on the IMG image can also upload avatar features
<div class= "Form-group" > <label for= "Avatar" class= "Col-sm-2 Control-label" > Avatar </label> <div class= "Col-sm-8" > <label for= "Avatar" ></label> <input type=" file "style=" Display:none; id= "Avatar" > </div></div>
Avatar preview FeatureThe picture preview function does not have anything to do with the backend, can get the path of the image that the user chooses by the front-end, then directly changes the SRC attribute of the IMG tag to the path of the user select picture, realizes the picture preview function
Portrait Preview $ ("#avatar"). Change (function () { var choose_file = $ (this) [0].files[0]; Instantiate a Reader object var reader = new FileReader (); Read the path of the file, no return value, results in Reader.result reader.readasdataurl (choose_file); Read takes time, after reading, then modify the picture path reader.onload=function () { $ ("#avatar_img"). attr ("src", This.result)} );
Here we use a user-selected file object method, first use $ ("#avatar") to upload the file's input tag of the jquery object, through $ ("#avatar") [0] to fetch the tag DOM object
Then through the DOM object's files method to get an array of uploaded files, and finally get the uploaded file object by index, that is, $ ("#avatar") [0].files[0]
After getting this object, in order to get the path of the file, we use the function of the reader
First instantiate a Reader object var reader = new FileReader (), reading the path of the file in the Readasdataurl method of the reader object
Since it takes time to read the file path, we bind an onload method to the reader object, and then change the SRC attribute of the IMG tag to the path of the file after the read is completed.
This enables the ability to preview the Avatar
Ajax Transfer filesDue to the need to pass files, if you use form table only son, you need to set enctype= "Multipart/form-data"
We use AJAX to send data, we need to use Formdata
$ (": Button"). Click (function () {///instance an object, which is used to encapsulate the data var formdata = new Formdata (); Formdata.append ("User", $ ("#id_user"). Val ()); Formdata.append ("nickname", $ ("#id_nickname"). Val ()); Formdata.append ("pwd", $ ("#id_pwd"). Val ()); Formdata.append ("Repeat_pwd", $ ("#id_repeat_pwd"). Val ()); Formdata.append ("Email", $ ("#id_email"). Val ()); Formdata.append ("Tel", $ ("#id_tel"). Val ()); Formdata.append ("Csrfmiddlewaretoken", $ ("[name= ' Csrfmiddlewaretoken ']"). Val ()); Formdata.append ("Avatar", $ ("#avatar") [0].files[0]); $.ajax ({url: "/register/", type: "Post", Data:formdata, Contenttype:false, Processdata:false, Success:function (data) {var data = json.parse (data); if (data.reg) {location.href= "/login/"}else{//Empty last error message $ ("form span"). HTML (" "); $ (". Form-group"). Removeclass ("Has-error"); var errors = data.error_msg; for (var i in errors) {if (i = = = "__all__") {//Border turns red $ ("#id_repeat_pwd"). Parent (). Parent (). addclass ("Has-error"); $ ("#id_repeat_pwd"). Next (). Text (Errors[i][0])}else{$ ("#id_" +i). Parent ( ). Parent (). addclass ("Has-error"); $ ("#id_" +i). Next (). Text (Errors[i][0])}}//You can also Use Each loop {# $.each (errors, function (field,error) {#}{# $ ("#id_" +field). Next (). Text (Error [0]) #}{# })#} } }) })
Note that this is going to add contenttype:false, Processdata:false, or it will go wrong.
Once you get the back-end data,First, the data returned by the backend is serialized, and then the data is returned by the key value pair to judge
If the data is not a problem, jump
If there is a problem with the data, you need to display the error message on the page
Because the key of the key-value pair of the error message returned by the backend corresponds to a field in the Form class, the ID of the input label of the page rendered by the object instantiated by the form class is the Id_ field, and the ID of each input box can be obtained by concatenation of the string.
The jquery object for each input box is taken, and the corresponding error message is displayed behind each input box.
Back-end data processingdef register (Request): Reg_info = {"Reg": True, "error_msg": ""} if Request.method = = "POST": form_obj = REGF ORM (Request. POST) if Form_obj.is_valid (): user = Form_obj.cleaned_data.get ("user") nickname = Form_obj.cleaned_ Data.get ("nickname") pwd = Form_obj.cleaned_data.get ("pwd") email = form_obj.cleaned_data.get ("email") Tel = form_obj.cleaned_data.get ("tel") avatar_obj = Request. Files.get ("Avatar") # Picture Object models. UserInfo.objects.create_user (Username=user, Password=pwd, Email=email, Telephone=tel, Nickname=nickname, avatar= Avatar_obj) # Add Avatar field automatically download the file, put it in the path after upload_to else: reg_info["error_msg"] = form_obj.errors reg_info["Reg"] = False return HttpResponse (Json.dumps (reg_info)) form_obj = RegForm () return Render (Request, "register.html", locals ())
Through the data from the front end, instantiate a Form_obj object, in the object through the Is_vaild () method to verify the data, if the data is not a problem, then extract the data from the Form_obj.cleaned_data, Adding data using the UserInfo.objects.create_user method
It should be noted here that the Avatar field, where we are directly using Avatar=avatar_obj This file object, in fact, in the database this field will still hold the path of the file, and the user uploaded files to the corresponding path
MediaIn the previous configuration, we have configured static file directories and aliases in the settings file to store some static files
In Django, users ' uploaded files are also uniformly placed in one place (similar to static configuration)
Class UserInfo (Abstractuser): " User Info" "" nid = models. Autofield (primary_key=true) nickname = models. Charfield (verbose_name= ' nickname ', max_length=32) telephone = models. Charfield (max_length=11, Null=true, unique=true) avatar = models. Filefield (upload_to= ' avatar_dir/', default= "/avatar/default.png") Create_time = models. Datetimefield (verbose_name= ' creation time ', auto_now_add=true) blog = models. Onetoonefield (to= ' Blog ', to_field= ' nid ', null=true)
For Filefield,imagefield fields:
Avatar = models. Filefield (upload_to = ' avatars/', default= "/avatar/default.png")
By default, the value avatars file that corresponds to the upload_to parameter in the Filefield field is downloaded to the project's root directory
If the settings is configured with a sentence:
Media_root=os.path.join (Base_dir, "blog", "Media")
Download the value avatars the upload_to parameter in the Filefield field to the Media_root path
Media_url = "/media/" # alias Media_root = Os.path.join (base_dir, "blog", "Media")
The configuration of the static file here is the same as the configuration type, except that the static configuration of the following content
Static_url = '/static/' staticfiles_dirs = [ os.path.join (Base_dir, "static")]
The user can access the static file directly through the path to the/static/file, because Django automatically configures the URL for you here.
And media here Django does not help you configure, so we need to configure ourselves in the URL
From django.conf.urls import urlfrom django.contrib import adminfrom Blog import viewsfrom django.views.static import serv Efrom s8_cnblog Import settingsurlpatterns = [ url (R ' ^admin/', admin.site.urls), url (r ' ^login/', views.log_in ), url (r ' ^get_valid_img/', views.get_valid_img), url (r ' ^index/', views.index), url (r ' ^logout/', views.logout), url (r ' ^register/', Views.register), # Media config url (r ' ^media/(? p<path>.*) $ ', serve, {' Document_root ': Settings. Media_root}),]
This way we can find the files uploaded by the user via the/media/path.
Blog Park-register (form component, Ajax submit data, Avatar Upload, media)