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()方法

 

posted @ 2017-12-17 10:31  百连  阅读(191)  评论(0编辑  收藏  举报