Django框架form表单配合ajax注册

Posted xu12135

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django框架form表单配合ajax注册相关的知识,希望对你有一定的参考价值。

总结一下,其实form组件的主要功能如下:

  • 生成页面可用的html标签
  • 对用户提交的数据进行校验
  • 保留上次输入内容

下面是写的登录页面的实例

1:views视图中的代码

# 注册页面
def register(request):
    if request.method == POST:
        # 将提交过来的数据放的form表单中进行校验
        form_obj = forms.Register(request.POST)
        # 判断校验是否真确
        print(form_obj.is_valid())
        ret = {status: False, msg: ‘‘}
        if form_obj.is_valid():

            # 删除form_obj.cleaned_data中的确认密码
            form_obj.cleaned_data.pop(re_password)
            avatar = request.FILES.get(avatar)
            models.UserInfo.objects.create_user(**form_obj.cleaned_data,avatar=avatar)
            ret[status] = True
            ret[msg] = /index/
            return JsonResponse(ret)
        else:
            ret[msg] = form_obj.errors

            return JsonResponse(ret)
    form_obj = forms.Register()
    return render(request, reg.html, {form_obj: form_obj})

2:forms表单中的代码

"""
注册使用的form表单
"""
from django import forms
from blog import models


class Register(forms.Form):
    username = forms.CharField(
        label=用户名:,
        max_length=16,
        error_messages={
            max_length: 用户名不能超过16位,
            required: 用户名不能为空
        },
        widget=forms.widgets.TextInput(
            attrs={class: form-control}
        )
    )
    password = forms.CharField(
        label=密码,
        min_length=6,
        error_messages={
            required: 密码不能为空,
            min_length: 密码不能少于6位,
        },
        widget=forms.widgets.PasswordInput(
            attrs={class: form-control},
            render_value=True
        )
    )
    re_password = forms.CharField(
        label=确认密码,
        min_length=6,
        error_messages={
            required: 确认密码不能为空,
            min_length: 确认密码不能少于6位,
        },
        widget=forms.widgets.PasswordInput(
            attrs={class: form-control},
            render_value=True
        )
    )
    email = forms.EmailField(
        label=邮箱,
        error_messages={
            invalid: 邮箱格式错误,
            required: 邮箱不能为空,
        },
        widget=forms.widgets.EmailInput(
            attrs={class: form-control}
        )
    )

    # 判断两次密码是否一致
    def clean_re_password(self):
        password = self.cleaned_data.get(password)
        re_password = self.cleaned_data.get(re_password)
        if password != re_password:
            raise forms.ValidationError(两次密码不一致)
        return re_password

    # 判断密码是否简单
    def clean_password(self):
        password = self.cleaned_data.get(password)
        if password == 123456:
            raise forms.ValidationError(密码太简单了)
        return password

    # 判断用户名是否存在
    def clean_username(self):
        username = self.cleaned_data[username]
        user_obj = models.UserInfo.objects.filter(username=username).first()
        if user_obj:
            raise forms.ValidationError(用户名已存在)
        return username

3:HTML中的代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Title</title>
    <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/mystyle.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3">
            <form novalidate action="/reg/" method="post" class="form-horizontal reg-form "
                  enctype="multipart/form-data">
                {% csrf_token %}
                <div class="form-group">
                    <label for="{{ form_obj.username.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.username.label }}</label>
                    <div class="col-sm-8 ">
                        {{ form_obj.username }}
                        <span class="help-block"></span>
                    </div>
                </div>

                <div class="form-group">
                    <label for="{{ form_obj.password.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.password.label }}</label>
                    <div class="col-sm-8 ">
                        {{ form_obj.password }}
                        <span class="help-block"></span>

                    </div>
                </div>

                <div class="form-group">
                    <label for="{{ form_obj.re_password.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.re_password.label }}</label>
                    <div class="col-sm-8 ">
                        {{ form_obj.re_password }}
                        <span class="help-block"></span>

                    </div>
                </div>

                <div class="form-group">
                    <label for="{{ form_obj.email.id_for_label }}"
                           class="col-sm-2 control-label">{{ form_obj.email.label }}</label>
                    <div class="col-sm-8 ">
                        {{ form_obj.email }}
                        <span class="help-block"></span>

                    </div>
                </div>

                <div class="form-group">
                    <label for="id_avatars"
                           class="col-sm-2 control-label">头像</label>
                    <div class="col-sm-8">
                        <label for="id_avatars">
                            <img src="/static/img/default.png" alt="" id="avatar-img">
                        </label>
                        <input id="id_avatars" name="avatars" type="file" style="display: none">
                    </div>
                </div>


                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button id="reg-submit" type="button" class="btn btn-success">注册</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
<script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap/js/bootstrap.min.js"></script>

4:ajax请求的代码

<script>
    $(#reg-submit).on(click, function () {
      // 上传带文件的ajax请求 需要将 data 类型 改为 FormData
        var formData = new FormData();
            formData.append(username,$("#id_username").val());
            formData.append(password,$(#id_password).val());
            formData.append(re_password,$("#id_re_password").val());
            formData.append(email,$(#id_email).val());
            formData.append(avatar,$(#id_avatars)[0].files[0]);
            formData.append(csrfmiddlewaretoken,$([name="csrfmiddlewaretoken"]).val());
        $.ajax({
            url: /reg/,
            type: POST,
            processData:false, // 文件上传必填的两项
            contentType:false,
            data: formData,
            success: function (data) {
                if (data.status) {
                    location.href = data.msg;
                } else {

                    $.each(data.msg,function (k,v) {

                       //console.log ($(#id_+k));
                        $(#id_+k).next().text(v[0]).parent().parent().addClass(has-error)
                    })
                }
            }
        })
    });
    // 获得焦点取消错误
    $(form input).focus(function () {
        $(this).next().text(‘‘).parent().parent().removeClass(has-error)
    });


    // 找到图片的input标签绑定change事件
    $(#id_avatars).change(function () {
        // 创建一个读取文件的对象
        var fileReader = new FileReader();
        // 1 取到当前选中的文件
        fileReader.readAsDataURL(this.files[0]);
        // 加载文件需要时间
        fileReader.onload = function () {
            // 加载完图片后添加到img标签中
            $(#avatar-img).attr(src, fileReader.result);
        }
    });
</script>

5:最后效果图

技术分享图片

以上是关于Django框架form表单配合ajax注册的主要内容,如果未能解决你的问题,请参考以下文章

Django框架 之 Form表单和Ajax上传文件

Django表单form ajax应用(上)

Django - AJAX - 如何提交多个表单?

使用Ajax验证并提交Django表单(django-crispy-forms)

使用ajax将它们作为json后如何循环遍历django表单错误

Django 框架篇: Django中的Form 组件