django利用不涉及数据库form自定义表单 表单元素验证

python 复制代码
from django import forms
from django.core.exceptions import ValidationError
class PerCenter(forms.Form):
    old_password = forms.CharField(label="旧密码", widget=forms.PasswordInput(attrs={'name': 'old_password'}))
    new_password = forms.CharField(label="新密码", widget=forms.PasswordInput(attrs={'name': 'new_password'}))
    confirm_password = forms.CharField(label="确认密码", widget=forms.PasswordInput(attrs={'name': 'confirm_password'}))

    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request',None)
        super(PerCenter, self).__init__(*args, **kwargs)

    def clean_old_password(self):
        old_password = self.cleaned_data.get('old_password')
        password = admin_app.models.UserInfo.objects.filter(username=self.request.user_name,password=md5(old_password)).first()
        if not password:
            raise ValidationError("旧密码错误")
        return password


    def clean_confirm_password(self):
        new_password = self.cleaned_data.get('new_password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if new_password != confirm_password:
            raise ValidationError("两次密码不一致")
        return md5(confirm_password)




def per_center(request):
    form=PerCenter(request=request)
    context={'form':form,
             }
    return render(request,"index/per_info.html",context)


@csrf_exempt
def modify_per_center(request):
    form = PerCenter(data=request.POST,request=request)
    if form.is_valid():
        print(form.cleaned_data)
        admin_app.models.UserInfo.objects.filter(id=request.session["info"]["id"]).update(password=form.cleaned_data["confirm_password"])
        return JsonResponse({"status":True})

    return JsonResponse({"status" : False , "error" : form.errors})

per_info.html

html 复制代码
  <div class="crm-profile-forms">
                <div>
                    <h2 class="crm-section-title">修改密码</h2>
                    <p class="crm-section-desc">定期更换密码有助于保护账号安全</p>
                </div>

                <form id="per-form-data">
                    {% for item in form %}
                    <div class="crm-form-group">
                        <label>{{ item.label }}</label>
                        {{ item }}
                    <span style="color: red"></span>
                    </div>
                    {% endfor %}



                </form>
            <button class="crm-form-btn" id="confirepwd">
                        保存密码
                    </button>
            </div>



    <script>
        submitPassword();
 

        function submitPassword() {
            $('#confirepwd').click(function () {
               $.ajax({
                url:"/modify/percenter/",
                type:"post",
                data:$("#per-form-data").serialize(),
                dataType:"JSON",
                success: function (res) {
                    alert(res.status)
                    if (res.status){
                        alert("修改成功")
                        //location.reload()
                    }else {
                        $.each(res.error, function (name, date) {
                            $("#id_"+name).next().text(date[0])
                        })
                    }
                }
            })
            })

        }
    </script>
相关推荐
Ashe8132 小时前
MySQL 慢日志先别急着加索引:三个指标能拦掉大半误判
数据库
ClouGence2 小时前
最基础的异构数据库 DDL 同步,我们踩过哪些坑?
数据库·mysql·postgresql
羑悻的小杀马特3 小时前
Redis持久化三剑客:RDB二进制快照、AOF文本日志、混合模式如何守护你的数据安全?
数据库·redis·缓存·aof·持久化存储·rdb
小呆爱发呆3 小时前
第三章 MySQL 库表操作
数据库·mysql·adb
时间的拾荒人4 小时前
Redis 进阶实战:渐进式遍历、持久化机制与事务详解
数据库·redis·缓存
普通人65 小时前
MySQL_FIND_IN_SET函数详解
android·数据库·mysql
真上帝的左手5 小时前
4. 关系型数据库-MySQL-Canal 进阶
数据库·mysql·canal
xiaoye-duck5 小时前
《C++ 项目:手写大模型接入 SDK》DataManager数据管理模块:SQLite持久化存储
开发语言·数据库·c++·sqlite
唐老板6 小时前
uuidv7 来了:为什么别再拿 uuidv4 当主键了
数据库