zoukankan      html  css  js  c++  java
  • 基于Form组件实现的增删改和基于ModelForm实现的增删改

    一、ModelForm的介绍

    复制代码
    ModelForm
        a.  class Meta:
                model,                           # 对应Model的
                fields=None,                     # 字段
                exclude=None,                    # 排除字段
                labels=None,                     # 提示信息
                help_texts=None,                 # 帮助提示信息
                widgets=None,                    # 自定义插件
                error_messages=None,             # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
                field_classes=None               # 自定义字段类 (也可以自定义字段)
                localized_fields=('birth_date',) # 本地化,如:根据不同时区显示数据
                如:
                    数据库中
                        2016-12-27 04:10:57
                    setting中的配置
                        TIME_ZONE = 'Asia/Shanghai'
                        USE_TZ = True
                    则显示:
                        2016-12-27 12:10:57
        b. 验证执行过程
            is_valid -> full_clean -> 钩子 -> 整体错误
    
    c. 字典字段验证
        </span><span style="color: #0000ff;">def</span><span style="color: #000000;"> clean_字段名(self):
            </span><span style="color: #008000;">#</span><span style="color: #008000;"> 可以抛出异常</span>
            <span style="color: #008000;">#</span><span style="color: #008000;"> from django.core.exceptions import ValidationError</span>
            <span style="color: #0000ff;">return</span> <span style="color: #800000;">"</span><span style="color: #800000;">新值</span><span style="color: #800000;">"</span><span style="color: #000000;">
    d. 用于验证
        model_form_obj </span>=<span style="color: #000000;"> XXOOModelForm()
        model_form_obj.is_valid()
        model_form_obj.errors.as_json()
        model_form_obj.clean()
        model_form_obj.cleaned_data
    e. 用于创建
        model_form_obj </span>=<span style="color: #000000;"> XXOOModelForm(request.POST)
        </span><span style="color: #008000;">#</span><span style="color: #008000;">### 页面显示,并提交 #####</span>
        <span style="color: #008000;">#</span><span style="color: #008000;"> 默认保存多对多</span>
            obj = form.save(commit=<span style="color: #000000;">True)
        </span><span style="color: #008000;">#</span><span style="color: #008000;"> 不做任何操作,内部定义 save_m2m(用于保存多对多)</span>
            obj = form.save(commit=<span style="color: #000000;">False)
            obj.save()      </span><span style="color: #008000;">#</span><span style="color: #008000;"> 保存单表信息</span>
            obj.save_m2m()  <span style="color: #008000;">#</span><span style="color: #008000;"> 保存关联多对多信息</span>
    
    f. 用于更新和初始化 obj = model.tb.objects.get(id=1) model_form_obj = XXOOModelForm(request.POST,instance=obj) ...
        PS: 单纯初始化
            model_form_obj </span>= XXOOModelForm(initial={...})</pre>
    
    复制代码

     应用场景:
                - ModelForm - 中小型应用程序。因为ModelForm是依赖于models的
                - Form      - 大型应用程序  *

    注意事项:

    复制代码
    注意事项:
                - 1. 类 
                      class Foo(ModelForm):
                        class Meta:
                            # model = models.Role
                            # fields = "__all__"
                            # fields = ['caption',]
                            # exclude = ['catpion']
                            model = models.UserType
                            fields = "__all__"
    
                        error_messages </span>=<span style="color: #000000;"> {
                            </span><span style="color: #800000;">'</span><span style="color: #800000;">title</span><span style="color: #800000;">'</span>:{<span style="color: #800000;">'</span><span style="color: #800000;">required</span><span style="color: #800000;">'</span>:<span style="color: #800000;">'</span><span style="color: #800000;">名称不能为空</span><span style="color: #800000;">'</span>,<span style="color: #800000;">'</span><span style="color: #800000;">invalid</span><span style="color: #800000;">'</span>:<span style="color: #800000;">'</span><span style="color: #800000;">格式错误</span><span style="color: #800000;">'</span><span style="color: #000000;">}
                        }
                        widgets </span>=<span style="color: #000000;"> {
                            </span><span style="color: #800000;">'</span><span style="color: #800000;">title</span><span style="color: #800000;">'</span>:wd.TextInput(attrs={<span style="color: #800000;">'</span><span style="color: #800000;">class</span><span style="color: #800000;">'</span>:<span style="color: #800000;">'</span><span style="color: #800000;">c1</span><span style="color: #800000;">'</span><span style="color: #000000;">})
                        }
                
            </span>- 2<span style="color: #000000;">. 添加
                 GET:
                    form </span>=<span style="color: #000000;"> Foo()
                 POST:
                    form </span>= Foo(data=<span style="color: #000000;">request.POST)
                    form.is_valid()
                    form.cleaned_data
                    form.erros
                    form.save()
            </span>- 3<span style="color: #000000;">. 修改
                 GET:
                    form </span>= Foo(instance=<span style="color: #000000;">obj)
                 
                 POST:
                    form </span>= Foo(instance=obj,dat=<span style="color: #000000;">request.POST)
                    ...
                    form.save()
                    </span></pre>
    
    复制代码

    二、表结构

    复制代码
    from django.db import models
    

    # Create your models here.
    class UserInfo (models.Model):
    username
    = models.CharField(max_length=32)
    email
    = models.EmailField(max_length=32)
    ut
    = models.ForeignKey("UserType")

    class UserType (models.Model):
    title
    = models.CharField(max_length=32)
    roles
    = models.ManyToManyField(to="Roles")
    def str(self):
    return self.title

    class Roles(models.Model):
    caption
    = models.CharField(max_length=32)
    def str(self):
    return self.caption

    复制代码

    三、基于Form组件的添加和编辑

    添加:这只是单表的添加

    复制代码
    from django.forms import Form, fields,widgets,ModelForm
    from django.shortcuts import render,redirect,HttpResponse
    from app01 import models
    # Create your views here.
    class RoleForm(Form):
        '''利用Form'''
        caption = fields.CharField(required=True,error_messages={"required":True})
    

    def role(request):
    role_obj
    = models.Roles.objects.all()
    print(role_obj)
    return render(request, "role.html",{"role_obj":role_obj})

    # 基于Form实现的
    def role_add(request):
    '''添加角色'''
    if request.method=="GET":
    form
    = RoleForm()
    return render(request,"role_add.html",{"form":form})
    else:
    form
    = RoleForm(data=request.POST)
    if form.is_valid():
    print("zzzzz")
    caption
    = form.cleaned_data.get("caption")
    models.Roles.objects.create(caption
    =caption)
    # models.Roles.objects.create(**form.cleaned_data)
    return redirect("/role/")
    else:
    return render(request,"role_add.html",{"form":form})

    复制代码

    编辑:单表的编辑

    复制代码
    #基于Form实现的编辑
    def role_edit(request,nid):
        obj = models.Roles.objects.filter(id=nid).first()
        print(obj.caption)
        if not obj :
            return HttpResponse("页面不存在")
        if request.method=="GET":
            form = RoleForm(initial={"caption":obj.caption})   #编辑的时候需要一个instance,让instance=一个你要编辑的那个对象
        else:
            form = RoleForm(data = request.POST)
            if form.is_valid():
                models.Roles.objects.filter(id=nid).update(**form.cleaned_data)
                return redirect("/role/")
        return render(request,"role_edit.html",{"form":form})
    复制代码

    具体基于Form组件实现的一对多添加或者多对多添加编辑详见博客http://www.cnblogs.com/haiyan123/p/7816877.html

    四、基于ModelForm的添加和编辑

    添加:单表的添加

    复制代码
    # 基于ModelForm的添加
    class RoleModelForm(ModelForm):
        class Meta:   #这个类必须写,而且名字必须是这个
            model = models.Roles   #这个model也是固定的,注意不加s,
            fields = "__all__"   #代表所有的字段,但是你也可以指定单个的字段
    

    def role_add(request):
    if request.method == "GET":
    form
    = RoleModelForm()
    return render(request,"role_add.html",{"form":form})
    else:
    form
    = RoleModelForm(data=request.POST)
    if form.is_valid():
    form.save()
    #这里直接可以用save方法,就把数据创建了
    return redirect("/role/")
    else:
    return render(request,"role_add.html",{"form":form})

    复制代码

    添加:多对多的添加,一堆多的提添加也是一样

    复制代码
    # 多对多的添加
    def usertype(request):
        user_type_list = models.UserType.objects.all()
        return render(request,"usertype.html",{'user_type_list':user_type_list})
    

    class UserTypeModelForm(ModelForm):
    title
    = fields.CharField(max_length=6,required=True,widget=widgets.Textarea) #这个字段是临时添加的,
    # 也就是说modelForm也可以用Form的方式。
    # 也可以以这样的方式新增字段, 如果有就覆盖,没有就增加;像现在这种情况就是吧下面的给覆盖了,当然没有上面的这个就用下面的了

    <span style="color: #0000ff;">class</span><span style="color: #000000;"> Meta:
        model </span>=<span style="color: #000000;"> models.UserType
        fields </span>= <span style="color: #800000;">"</span><span style="color: #800000;">__all__</span><span style="color: #800000;">"</span><span style="color: #000000;">
    
        error_messages </span>=<span style="color: #000000;"> {
            </span><span style="color: #800000;">"</span><span style="color: #800000;">title</span><span style="color: #800000;">"</span>:{<span style="color: #800000;">"</span><span style="color: #800000;">required</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">用户名不能为空</span><span style="color: #800000;">"</span>,<span style="color: #800000;">"</span><span style="color: #800000;">invalid</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">邮箱格式不一致</span><span style="color: #800000;">"</span><span style="color: #000000;">}
        }
        widgets </span>=<span style="color: #000000;"> {
            </span><span style="color: #800000;">"</span><span style="color: #800000;">title</span><span style="color: #800000;">"</span>:widgets.TextInput(attrs={<span style="color: #800000;">"</span><span style="color: #800000;">class</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">c1</span><span style="color: #800000;">"</span><span style="color: #000000;">})
        }
    

    def usertype_add(request):
    '''多对多的添加'''
    if request.method=="GET":
    modelform
    = UserTypeModelForm()
    return render(request,"usertype_add.html",{"modelform":modelform})
    else:
    modelform
    = UserTypeModelForm(data=request.POST)
    if modelform.is_valid():
    modelform.save()
    #也可以用save来实现,就连关系表的字段也都添加了
    return redirect("/usertype/")
    else:
    return render(request, "usertype_add.html", {"modelform": modelform})

    复制代码

    编辑:单表的编辑

    复制代码
    # 基于modelForm实现的编辑
    def role_edit(request,nid):
        obj = models.Roles.objects.filter(id=nid).first()
        if not obj :
            return HttpResponse("页面不存在")
        if request.method=="GET":
            form = RoleModelForm(instance=obj)   #编辑的时候需要一个instance,让instance=一个你要编辑的那个对象
        else:
            form = RoleModelForm(data = request.POST,instance=obj)
            if form.is_valid:
                form.save()
                return redirect("/role/")
        return render(request,"role_edit.html",{"form":form})
    复制代码

    编辑:多对多的编辑

    复制代码
    # 多对多的编辑
    def usertype(request):
        user_type_list = models.UserType.objects.all()
        return render(request,"usertype.html",{'user_type_list':user_type_list})
    

    class UserTypeModelForm(ModelForm):
    title
    = fields.CharField(max_length=6,required=True,widget=widgets.Textarea) #这个字段是临时添加的,
    # 也就是说modelForm也可以用Form的方式。
    # 也可以以这样的方式新增字段, 如果有就覆盖,没有就增加;像现在这种情况就是吧下面的给覆盖了,当然没有上面的这个就用下面的了

    <span style="color: #0000ff;">class</span><span style="color: #000000;"> Meta:
        model </span>=<span style="color: #000000;"> models.UserType
        fields </span>= <span style="color: #800000;">"</span><span style="color: #800000;">__all__</span><span style="color: #800000;">"</span><span style="color: #000000;">
    
        error_messages </span>=<span style="color: #000000;"> {
            </span><span style="color: #800000;">"</span><span style="color: #800000;">title</span><span style="color: #800000;">"</span>:{<span style="color: #800000;">"</span><span style="color: #800000;">required</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">用户名不能为空</span><span style="color: #800000;">"</span>,<span style="color: #800000;">"</span><span style="color: #800000;">invalid</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">邮箱格式不一致</span><span style="color: #800000;">"</span><span style="color: #000000;">}
        }
        widgets </span>=<span style="color: #000000;"> {
            </span><span style="color: #800000;">"</span><span style="color: #800000;">title</span><span style="color: #800000;">"</span>:widgets.TextInput(attrs={<span style="color: #800000;">"</span><span style="color: #800000;">class</span><span style="color: #800000;">"</span>:<span style="color: #800000;">"</span><span style="color: #800000;">c1</span><span style="color: #800000;">"</span><span style="color: #000000;">})
        }
    

    def usertype_edit(request,nid):
    #查出当前类型用户对应的角色
    obj = models.UserType.objects.filter(id =nid).first()
    if not obj:
    return HttpResponse("页面不存在")
    if request.method =="GET":
    form
    = UserTypeModelForm(instance=obj)
    return render(request,"usertype_edit.html",{"form":form})
    else:
    form
    = UserTypeModelForm(instance=obj,data=request.POST)
    if form.is_valid():
    form.save()
    return redirect("/usertype/")
    return render(request,"usertype_edit.html",{"form":form})

    复制代码
  • 相关阅读:
    Vi 和 Vim
    The C Programming Language-Chapter 5 Pointers and Arrays
    C# 4.0开始,泛型接口和泛型委托都支持协变和逆变
    数据库中的锁 and java StampedLock ReadWriteLock
    NetCore and ElasticSearch 7.5
    网关项目 ReverseProxy
    异常捕获&打印异常信息
    刷新:重新发现.NET与未来
    2019 中国.NET 开发者峰会正式启动
    .NET开发者必须学习.NET Core
  • 原文地址:https://www.cnblogs.com/maaosheng/p/11621454.html
Copyright © 2011-2022 走看看