Instance Code for Registration Function Based on Ajax and Forms Components

Time:2019-7-12

Front-end HTML

<!DOCTYPE html>
{% load static %}
{% get_static_prefix as getstatic %}
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="x-ua-compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" href="https://www.jd.com/favicon.ico">
  <link href="{{ getstatic }}plugins/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
  < title > registration page </title >
  <style>
    .title-top {
      padding: 0;
      font-size: 21px;
      margin-top: 40px;
    }
    .form-padding {
      padding-right: 65px;
    }
    .has-feedback .country-code {
      width: 53px;
      text-align: right;
      padding-right: 5px;
    }
    .mobile-control-wrap {
      display: flex;
    }
    .mobile-num {
      margin-left: 10px;
    }
    .form-horizontal .form-group {
      margin-right: -15px;
      margin-left: -15px;
    }
    .body-box {
      margin-top: 70px;
      height: 567px;
      width: 68%;
    }
    .cnblogs-btn-blue {
      color: white;
      padding: 6px 14px;
      letter-spacing: 1em;
      padding-left: 2em;
      background-color: RGB(70, 136, 214);
      text-align: center;
    }
    .cnblogs-btn-blue :hover {
      color: white;
    }
    .navbar {
      background-color: RGB(40, 62, 92);
    }
    .side-img-box {
      height: 300px;
      position: relative;
      padding-left: 0;
      margin-top: 168px;
    }
    .side-img-box img {
      position: relative;
      width: 100%;
      top: 50%;
      transform: translateY(-50%);
      border-radius: 8px;
    }
    .text-danger {
      float: right;
    }
    .img-thumbnail {
      width: 100px;
      height: 100px;
      margin-bottom: 20px;
      margin-top: -10px;
    }
    #avatr_img {
      margin-left: 237px;
    }
  </style>
</head>
<body>
<nav>
  <div>
    <!-- Brand and toggle get grouped for better mobile display -->
    <div>
      <img src="{getstatic}}} img/TIM screenshot 201 80205110238.png">
    </div>
    <!-- Collect the nav links, forms, and other content for toggling -->
    <div>
      <ul>
        <li> <a href=""> Home page</a></li>
        <li> <a href=""> Log on</a></li>
        <li> <a href=""> Registration</a></li>
        <li> <a href=""> Help</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
</nav>
<div style="height: 567px;">
  <div>
    <! - Head Tips - >
    <div>
      Register new users
      <hr>
    </div>
    <div>
      <form role="form" method="post"
         novalidate="novalidate">
        <! - Every line - >
        <div>
          <label for="avatar">
            <img src="{getstatic}}} img/registers ideimg.png" alt= "user avatar">
            Head portrait
          </label>  
          <input type="file" style="display: none;">
        </div>
        <div>
          <div>
            <label for="Email">Mail>Box</label>
          </div>
          <div>
            {{ register_form.email }}
            <span></span>
          </div>
        </div>
        <div>
          <div>
            <label for="DisplayName">nickname </label>
          </div>
          <div>
            {{ register_form.nik_name }}
            <span><span></span></span>
          </div>
        </div>
        <div>
          <div>
            <label for="Password">secret code </label>
          </div>
          <div>
            {{ register_form.password }}
            <span></span>
          </div>
        </div>
        <div>
          <div>
            <label for="Confirm Password">Confirmation Password </label>
          </div>
          <div>
            {{ register_form.repeta_pwd }}
            <span><span></span></span>
          </div>
        </div>
        <! - Registration button - >
        <div>
          <div>
            <span></span>
            <input onclick="regesite()" type="button"
                Value= "login">
          </div>
        </div>
        <! - Agreement Tips - >
        <div>
          <span>* The </span> Registration button means that you agree and are willing to comply with <a target="_blank"
                                      Href="//passport.cnblogs.com/agreement.html"> User Protocol </a>.
        </div>
        <!--hidden-->
        {% csrf_token %}
      </form>
      <div>
        <div>
          <div></div>
        </div>
        <img src="{{ getstatic }}img/registersideimg.png">
      </div>
    </div>
  </div>
</div>
<script src="{{ getstatic }}js/jquery-3.2.1.min.js"></script>
<script src="{{ getstatic }}plugins/bootstrap-3.3.7/js/bootstrap.min.js"></script>
</body>
</html>

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

<script>
   $("#avatar").change(function () {
    var chooice_file = $(this)[0].files[0];
    Var reader = new FileReader (); // Note here, preview local files
    reader.readAsDataURL(chooice_file);
    reader.onload=function () {
      $("#avatar_img").attr("src",this.result)
    }
  })
  function regesite() {
    Var formdata = new FormData (); //z Note that file upload is involved here
    formdata.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").html("")
          $(".has-feedback").removeClass("has-error")
          $.each(response_data.error_msg,function (fiel, error_info) {
            // Display error message
            $("#id_"+fiel).parent().addClass("has-error");
            $("# id_"+fiel). next (). HTML (error_info [0]); // Display global error // Note here
            if(fiel=="__all__"){
              $("#id_repeta_pwd").next().html(error_info[0]).css("color","red")
            }
          })
        }
      }
    })
  }
</script>

FileReader

FileReader is mainly used to read the contents of files into memory. Through a series of asynchronous interfaces, local files can be accessed in the main thread.

Using FileReader objects, web applications can read the contents of files (or raw data buffers) stored on the user’s computer asynchronously. File objects or Blob objects can be used to specify the files or data to be processed.

Design RegisterForm Components

from django import forms
from . import models
from django.forms import widgets
from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
class RegisterForm(forms.Form):
  nik_name = forms.CharField(max_length=32,
                widget=widgets.TextInput(attrs={"class":"form-control"}),
                Error_messages={"required": "Users can't be empty"}
  email = forms.EmailField(widget=widgets.EmailInput(attrs={"class":"form-control"}),
               Error_messages={"required": "mailbox cannot be empty", "invalid", "mailbox format error"}
  password = forms.CharField(min_length=5, widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                Error_messages={"required": "Password cannot be empty"
                        "Min_length": "Minimum length 5 bits".
                        }
                )
  repeta_pwd = forms.CharField(widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                 Error_messages={"required": "Password cannot be empty"}
  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 Validation Error ("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 Validation Error ("two password inconsistencies")
    else:
      return self.cleaned_data

The 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")# Note the request. FILES. get (") used here.
      if not valid:
        Valid = avatardir / TIM picture 20171209211626. gif
      check_user = models.UserInfo.objects.create_user(username=nik_name,nik_name=nik_name, email=email,
                                password=password,
                                avatar=valid
                              )# Note that the image path is saved in the guide database, not the picture.
      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")

Be careful:

Upload_to: Create folders to the root directory by default. If created to a specified location, you need to configure media in settings.

For example, you want the files uploaded by users to be stored separately and configured in settings.

MEDIA_ROOT= os.path.jion(BASE_DIR,"blog","media")
// At this point, when users upload files, they first create and save the files to the "putImg" folder, "putImg", and then put "putImg" into the corresponding path.
# Media configuration
url(r"^media/(?P<path>.*)",sever,{"document_root":setting.MEDIA_ROOT})

After configuring the URL above, users can access all the files under the media folder

Be careful:

Server, imported from django. views. static import server
     Use from. import settings //url

summary

Above mentioned is the implementation of registration function based on Ajax and Forms components introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message, Xiaobian will reply to you in time. Thank you very much for your support to developpaer.