Home  >  Article  >  Web Front-end  >  Use Ajax and forms to implement the functions required to register users

Use Ajax and forms to implement the functions required to register users

php中世界最好的语言
php中世界最好的语言Original
2018-03-30 15:15:481808browse

This time I will bring you the functions required for registered users using Ajax and forms. What are the precautions for using Ajax and forms to realize the functions required for registered users? Here are practical cases, let’s take a look.

Front-end HTML


{% load static %}
{% get_static_prefix as getstatic %}


  
  
  
  
  
  注册页面
  

  

         


    

    

      

                 

                                

        

          

                       

          

            {{ register_form.email }}                        

        

        

          

                       

          

            {{ register_form.nik_name }}                        

        

        

          

                       

          

            {{ register_form.password }}                        

        

        

          

                       

          

            {{ register_form.repeta_pwd }}                        

        

                 

          

                                    

        

                 

          * “注册” 按钮,即表示您同意并愿意遵守 用户协议。         

                 {% csrf_token %}       
      

          

        

               

    

  

The above code is just HTML, and JavaScript is in the example below

FileReader

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

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

Design RegisterForm component

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":"用户不能为空"})
  email = forms.EmailField(widget=widgets.EmailInput(attrs={"class":"form-control"}),
               error_messages={"required":"邮箱不能为空", "invalid":"邮箱格式错误"})
  password = forms.CharField(min_length=5, widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                error_messages={"required": "密码不能为空",
                        "min_length":"最小长度5位",
                        }
                )
  repeta_pwd = forms.CharField(widget=widgets.PasswordInput(attrs={"class":"form-control"}),
                 error_messages={"required": "密码不能为空"})
  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("用户已存在")
  def clean(self): //全局钩子
    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("两次密码不一致")
    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") #注意这里使用的request.FILES.get("")
      if not valid:
        valid = "avatardir/TIM图片20171209211626.gif"
      check_user = models.UserInfo.objects.create_user(username=nik_name,nik_name=nik_name, email=email,
                                password=password,
                                avatar=valid
                              ) # 注意这里保存导数据库中的是图片路径,并不是图片
      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))

Userifor's img

avatar = models.FileField(upload_to='avatar/', default="/avatar/default.gif", verbose_name="主键")

Note:

upload_to: By default, the folder is created to In the root directory, if you create it to a specified location, you need to configure media in the setting.

For example: you want the files uploaded by the user to be stored separately and configured in the setting.

MEDIA_ROOT= os.path.jion(BASE_DIR,"blog","media")
//此时,用户上传文件时,先创建并将文件保存至“putImg”文件夹中,“putImg”,然后将“putImg”放至对应的路径中。
# media 配置
url(r"^media/(?P.*)",sever,{"document_root":setting.MEDIA_ROOT})

After configuring the above url, the user can access all files under the media folder

Note:

 server ,是从django.views.static import server导入
     from . import settings //url中的使用

I believe you have mastered the method after reading the case in this article, please pay attention for more exciting things Other related articles on php Chinese website!

Recommended reading:

Native Ajax implementation MIME type (with code)

Determine whether it is an integer, decimal or What are the ways to write regular numbers for real numbers

The above is the detailed content of Use Ajax and forms to implement the functions required to register users. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn