• ModelForm


    1、引入

    from django.forms imoprt ModelForm
    from django.forms import widgets as wd

    2、前戏

    models.py:

    from django.db import models
    
    class Role(models.Model):
        caption = models.CharField(max_length=32)
    
        def __str__(self):
            return self.caption
    class UserType(models.Model):
        title = models.CharField(max_length=32)
        roles = models.ManyToManyField('Role')
    
    class UserInfo(models.Model):
        name = models.CharField(max_length=32)
        email = models.EmailField(max_length=32)
    
        ut = models.ForeignKey('UserType')
    

      

    3、视图

    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
    
    # class Role(Form):
    #     caption = fields.CharField(max_length=32,required=True)
    #
    # 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():
    #             models.Role.objects.create(**form.cleaned_data)
    #             # models.Role.objects.create(**{'catpion':'123'})
    #         else:
    #             return render(request, 'role_add.html', {'form': form})
    
    
    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__"       # 所有字段
    		# fields = ['caption',]
    		# exclude = ['catpion']
            error_messages = {
                'title':{'required':'名称不能为空','invalid':'格式错误'}
            }                        # 错误信息
            widgets = {
                'title':wd.TextInput(attrs={'class':'c1'})
            }                        # 定制指定字段的input框类型及属性
    
        # 支持钩子函数
    
    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) # 把拿到的数据传入form中进行校验
            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) # 括号内两个参数都不能少,一个是原记录(instance),一个是传过来的值(data),这样可以做到更新操作
            if form.is_valid():
                form.save()                                         # 更新后的值更新到数据库(不是新建)
                return redirect('/usertype/')
            else:
                return render(request, 'user_type_edit.html', {'form': form})
    

      4、前端

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta 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>
    </head>
    <body>
        <form method="post" novalidate>
            {% csrf_token %}
            {{ form.as_p }}
            <input type="submit" value="提交">
        </form>
    </body>
    </html>
    

      

     当你生成的form表单中排除了一些字段的值后,当你应用form.save()方法时会报错,需要使用

    form.instance.field_name = value
    

      方式,来把不全的字段补齐然后再执行form.save()方法

  • 相关阅读:
    C#结构体指针的定义及使用详解
    C# out和ref关键字
    CListCtrl控件主要事件及LVN_ITEMCHANGED消息和鼠标双击列表项事件的处理
    深圳职位:替朋友招聘biztalk的技术人员 无为而为
    微软出最新SQL Server 2005 累积修补程序包(版本 9.0.2153)(200684),这是SP1之后的更新 无为而为
    微软Visual Studio 2005 SDK version 3.0 发布了,TFS扩展的开发人员/DSL/VSTS Test都应该关注 无为而为
    好东西,将你的英文版TFS变为中文版?:Visual Studio 2005 Team Foundation Server 语言更改包 无为而为
    Analysis Service计算[期间增长率]的若干注意 无为而为
    亲身体验:更改 Team Foundation Server 部署的语言版本是一个复杂耗时的过程 无为而为
    各大门户调查:鄙视新浪,将博士伦的广告挂在热点新闻中间好几天了,把大众当傻瓜 无为而为
  • 原文地址:https://www.cnblogs.com/wangbaihan/p/8051497.html
Copyright © 2020-2023  润新知