Django框架form表單配合ajax註冊

總結一下,其實form組件的主要功能以下:css

  • 生成頁面可用的HTML標籤
  • 對用戶提交的數據進行校驗
  • 保留上次輸入內容

下面是寫的登陸頁面的實例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:最後效果圖

相關文章
相關標籤/搜索