Instance Code for Registration Function Based on Ajax and Forms Components


Front-end HTML

<!DOCTYPE html>
{% load static %}
{% get_static_prefix as getstatic %}
<html lang="zh-CN">
  <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="">
  <link href="{{ getstatic }}plugins/bootstrap-3.3.7/css/bootstrap.min.css" rel="stylesheet">
  < title > registration page </title >
    .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;
    <!-- Brand and toggle get grouped for better mobile display -->
      <img src="{getstatic}}} img/TIM screenshot 201 80205110238.png">
    <!-- Collect the nav links, forms, and other content for toggling -->
        <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>
    </div><!-- /.navbar-collapse -->
  </div><!-- /.container-fluid -->
<div style="height: 567px;">
    <! - Head Tips - >
      Register new users
      <form role="form" method="post"
        <! - Every line - >
          <label for="avatar">
            <img src="{getstatic}}} img/registers ideimg.png" alt= "user avatar">
            Head portrait
          <input type="file" style="display: none;">
            <label for="Email">Mail>Box</label>
            {{ }}
            <label for="DisplayName">nickname </label>
            {{ register_form.nik_name }}
            <label for="Password">secret code </label>
            {{ register_form.password }}
            <label for="Confirm Password">Confirmation Password </label>
            {{ register_form.repeta_pwd }}
        <! - Registration button - >
            <input onclick="regesite()" type="button"
                Value= "login">
        <! - Agreement Tips - >
          <span>* The </span> Registration button means that you agree and are willing to comply with <a target="_blank"
                                      Href="//"> User Protocol </a>.
        {% csrf_token %}
        <img src="{{ getstatic }}img/registersideimg.png">
<script src="{{ getstatic }}js/jquery-3.2.1.min.js"></script>
<script src="{{ getstatic }}plugins/bootstrap-3.3.7/js/bootstrap.min.js"></script>

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

   $("#avatar").change(function () {
    var chooice_file = $(this)[0].files[0];
    Var reader = new FileReader (); // Note here, preview local files
    reader.onload=function () {
  function regesite() {
    Var formdata = new FormData (); //z Note that file upload is involved here
      url: "{% url "regeste" %}",
      type: "POST",
      success: function (data) {
        response_data = JSON.parse(data)
          location.href="{% url " rel="external nofollow" login" %}"
        }else {
          // Clear the last error message
          $("form span").html("")
          $.each(response_data.error_msg,function (fiel, error_info) {
            // Display error message
            $("# id_"+fiel). next (). HTML (error_info [0]); // Display global error // Note here


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,
                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
      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
        Raise Validation Error ("two password inconsistencies")
      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,
                              )# 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))
      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

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


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.