The instance code that implements the registration function based on Ajax and forms components, ajaxforms

Source: Internet
Author: User
Tags import database

The instance code that implements the registration function based on Ajax and forms components, ajaxforms

Front-end HTML

<! DOCTYPE html >{% load static % }{% get_static_prefix as getstatic %} 

The above code is only HTML, while JavaScript is in the following example.

<Script> $ ("# avatar "). change (function () {var chooice_file = $ (this) [0]. files [0]; var reader = new FileReader (); // You can preview the local file reader. readAsDataURL (chooice_file); reader. onload = function () {$ ("# avatar_img "). attr ("src", this. result)}) function regesite () {var formdata = new FormData (); // note that the file upload formdata is involved here. append ("email", $ ("# id_email "). val (); formdata. append ("nik_name", $ ("# id_nik_name "). val (); formdata. append ("password", $ ("# id_password "). val (); formdata. append ("repeta_pwd", $ ("# id_repeta_pwd "). val (); formdata. append ("valid_img", $ ("# avatar") [0]. files [0]); formdata. append ("csrfmiddlewaretoken", $ ("[name = 'csrfmiddlewaretoken ']"). val (); $. ajax ({url: "{% url" regeste "%}", type: "POST", data: formdata, contentType: false, processData: false, success: function (data) {response_data = JSON. parse (data) if (response_data.user) {location. href = "{% url" rel = "external nofollow" login "%}"} else {// clear the last error message $ ("form span" pai.html ("") $ (". has-feedback "). removeClass ("has-error") $. each (response_data.error_msg, function (fiel, error_info) {// Display Error Information $ ("# id _" + fiel ). parent (). addClass ("has-error"); $ ("# id _" +fiel).next().html (error_info [0]); // display a global error // note that if (fiel = "_ all _") {$ ("# id_repeta_pwd" pai.next().html(error_info1_000000000.css ("color ", "red") }}}}) }</script>

FileReader

FileReader is mainly used to read file content into the memory. It can access local files in the main thread through a series of asynchronous interfaces.

With the FileReader object, web applications can asynchronously read files (or raw data buffering) stored on users' computers, you can use a File object or Blob Object to specify the File or data to be processed.

Design the RegisterForm component

From django import formsfrom. import modelsfrom django. forms import widgetsfrom django. core. exceptions import NON_FIELD_ERRORS, ValidationErrorclass RegisterForm (forms. form): nik_name = forms. charField (max_length = 32, widget = widgets. textInput (attrs = {"class": "form-control"}), error_messages = {"required": "the user cannot be blank"}) email = forms. emailField (widget = widgets. emailInput (attrs = {"class": "form-control"}), error_messages = {"required": "email cannot be blank", "invalid ": "Incorrect email format"}) password = forms. charField (min_length = 5, widget = widgets. passwordInput (attrs = {"class": "form-control"}), error_messages = {"required": "The password cannot be blank.", "min_length ": "minimum length of 5 characters",}) repeta_pwd = forms. charField (widget = widgets. passwordInput (attrs = {"class": "form-control"}), error_messages = {"required": "The password cannot be blank"}) def clean_nik_name (self ): name = self. cleaned_data.get ("nik_name") users = models. userInfo. objects. filter (nik_name = name) if not users: return name else: raise ValidationError ("User already exists") def clean (self): // global hook pwd = self. cleaned_data.get ("password") repeta_pwd = self. cleaned_data.get ("repeta_pwd") if pwd and repeta_pwd: if pwd = repeta_pwd: return self. cleaned_data else: raise ValidationError ("two passwords inconsistent") else: return self. cleaned_data

Server

Def post (self, request): reg_response = {"user": None, "error_msg": ""} register_form = RegisterForm (request. POST) if register_form.is_valid (): email = request. POST. get ("email") nik_name = request. POST. get ("nik_name") password = request. POST. get ("password") repeta_pwd = request. POST. get ("repeta_pwd") valid = request. FILES. get ("valid_img") # Pay attention to the request used here. FILES. get ("") if not valid: valid = "avatardir/timimage 20171209242626.gif" check_user = models. userInfo. objects. create_user (username = nik_name, nik_name = nik_name, email = email, password = password, avatar = valid) # Save the image path in the import database, not the image reg_response = {"user": "user", "error_msg": ""} return HttpResponse (json. dumps (reg_response) else: reg_response ["error_msg"] = register_form.errors return HttpResponse (json. dumps (reg_response ))

Img of Userifor in Model

Avatar = models. FileField (upload_to = 'Avatar/', default = "/avatar/default.gif", verbose_name = "primary key ")

Note:

Upload_to: by default, the folder is created under the root directory. To create a folder to a specified location, you must configure media in setting.

For example, if you want to store the uploaded files separately, configure it in setting,

MEDIA_ROOT = OS. path. jion (BASE_DIR, "blog", "media") // when you upload a file, create and save the file to the putImg folder ", then put "putImg" in the corresponding path. # Media configuration url (r "^ media /(? P <path>. *) ", sever, {" document_root ": setting. MEDIA_ROOT })

After the preceding url is configured, you can access all files in the media folder.

Note:

Server, which is used to import from. import settings // url from django. views. static import server

Summary

The above section describes how to implement the registration function based on Ajax and forms components. I hope it will help you. If you have any questions, please leave a message and I will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.