zoukankan      html  css  js  c++  java
  • Django之Modelform组件

    Modelform组件

    Modelform就是model和from两者结合起来的。它既有验证,又有数据库的操作

    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. 字典字段验证
            def clean_字段名(self):
                # 可以抛出异常
                # from django.core.exceptions import ValidationError
                return "新值"
        d. 用于验证
            model_form_obj = 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 = XXOOModelForm(request.POST)
            #### 页面显示,并提交 #####
            # 默认保存多对多
                obj = form.save(commit=True)
            # 不做任何操作,内部定义 save_m2m(用于保存多对多)
                obj = form.save(commit=False)
                obj.save()      # 保存单表信息
                obj.save_m2m()  # 保存关联多对多信息
     
        f. 用于更新和初始化
            obj = model.tb.objects.get(id=1)
            model_form_obj = XXOOModelForm(request.POST,instance=obj)
            ...
     
            PS: 单纯初始化
                model_form_obj = XXOOModelForm(initial={...})

    Modelform注意事项:

    1、类

      class Foo(ModelFrom):
           class Meta:
    model=models.Role
    #fields="__all__" 所有的字段 #fields=['caption',] 只取caption这个字段
    #xclude=['caption'] 除caption这个字段外不取,剩余的都取
    error_massages={
    'title':{'required':'名称不能为空','invalid':'格式错误'}
    }
    widgets={
    'title':wd.TextInput(attrs={'class':'c1'})
    }
    2.添加:
    GET:
    form=Foo()
    POST:
    form=Foo(instaance=obj,data=request.POST)
    form.save()

    示列(增删改查):

    url:

    from django.conf.urls import url
    from django.contrib import admin
    from app01 import views
    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^role/$', views.role),
        url(r'^role/add/$', views.role_add),
        url(r'^role/edit/(d+)/$', views.role_edit),
        url(r'^usertype/$', views.user_type),
        url(r'^usertype/add/$', views.user_type_add),
        url(r'^usertype/edit/(d+)/$', views.user_type_edit),
        #url(r'^role.html$', admin.site.urls),
    ]
    url

    views:

    from django.shortcuts import render,redirect,HttpResponse
    from app01 import models
    
    
    from django.forms import Form,ModelForm
    from django.forms import fields
    from django.forms import widgets as wd
    
    
    
    
    def role(request):
        roles = models.Role.objects.all()
        return render(request,'role.html',{'roles':roles})
    
    
    class Role(ModelForm):
    
        class Meta:
            model = models.Role
            fields = "__all__"
    
    
    def role_add(request):
        if request.method == "GET":
            form = Role()
            return render(request,'role_add.html',{'form':form})
        else:
            form = Role(request.POST)
            if form.is_valid():
                form.save()
                # models.Role.objects.create(**form.cleaned_data)
                # models.Role.objects.create(**{'catpion':'123'})
                return redirect('/role/')
            else:
                return render(request, 'role_add.html', {'form': form})
    
    
    def role_edit(request,nid):
        obj = models.Role.objects.filter(id=nid).first()
        if not obj:
            return HttpResponse('数据不存在')
    
        if request.method == "GET":
            form = Role(instance=obj)
            return render(request,'role_edit.html',{'form':form})
        else:
            form = Role(data=request.POST,instance=obj)
            if form.is_valid():
                form.save()
                return redirect('/role/')
            else:
                return render(request, 'role_edit.html', {'form': form})
    
    
    def user_type(request):
        user_type_list = models.UserType.objects.all()
        return render(request,'user_type.html',{'user_type_list':user_type_list})
    
    class UserTypeModeForm(ModelForm):
        title = fields.CharField(max_length=6,required=True,widget=wd.Textarea())
    
        class Meta:
            model = models.UserType
            fields = "__all__"
    
            error_messages = {
                'title':{'required':'名称不能为空','invalid':'格式错误'}
            }
            widgets = {
                'title':wd.TextInput(attrs={'class':'c1'})
            }
    
        # 钩子函数
    
    def user_type_add(request):
        if request.method == "GET":
            form = UserTypeModeForm()
            return render(request,'user_type_add.html',{'form':form})
        else:
            form = UserTypeModeForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('/usertype/')
            else:
                return render(request, 'user_type_add.html', {'form': form})
    
    
    def user_type_edit(request,nid):
        obj = models.UserType.objects.filter(id=nid).first()
        if not obj:
            return HttpResponse('...')
    
        if request.method == 'GET':
            # 显示默认值
            form = UserTypeModeForm(instance=obj)
            return render(request,'user_type_edit.html',{'form':form})
        else:
            form = UserTypeModeForm(instance=obj,data=request.POST)
            if form.is_valid():
                form.save()
                return redirect('/usertype/')
            else:
                return render(request, 'user_type_edit.html', {'form': form})
    Views

    role.html:

    </head>
    <body>
        <ul>
            {% for row in roles %}
                <li>{{ row.caption }}</li>
            {% endfor %}
        </ul>
    </body>
    </html>
    role.html

    role_add.html:

    <body>
        <form method="post">
            {% csrf_token %}
            <p>{{ form.caption }} {{ form.errors.caption.0 }}</p>
            <input type="submit" value="提交">
        </form>
    </body>
    role_add

    role_edit.html:

    <body>
        <form method="post">
            {% csrf_token %}
            <p>{{ form.caption }} {{ form.errors.caption.0 }}</p>
            <input type="submit" value="提交">
        </form>
    </body>
    role_edit.html

    user_type.html

    <body>
        <ul>
            {% for row in user_type_list %}
                <li>{{ row.title }} - {{ row.roles.all }}</li>
            {% endfor %}
        </ul>
    </body>
    user_type.html

    user_type_add.html

    <body>
        <form method="post">
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="提交">
        </form>
    </body>
    user_type_add.html

    user_type_edit.html

    <body>
        <form method="post" novalidate>
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="提交">
        </form>
    </body>
    user_type_edit.html

     

        

  • 相关阅读:
    IOS:APP网络状态的检测
    IOS:个人笔记|UI__使用Plist文件来进行数据的读取
    IntelliJ IDEA中项目import与open的区别
    打开电脑分屏
    微服务
    自增主键和UUID
    雪花算法
    使用navicat连接阿里云上mysql
    【vue】报错This dependency was not found
    跨域问题
  • 原文地址:https://www.cnblogs.com/mengqingjian/p/7994311.html
Copyright © 2011-2022 走看看