Loading

Django - ModelForm

modelform的常用配置

from django import forms
from django.forms import widgets as wid


class ProjectForm(forms.ModelForm):
    class Meta:
        model = models.Project
        # fields = "__all__"
        exclude = ['project_status']  # 排除哪些字段
        labels = {
            "project_name": "项目名称",
            "project_detail": "项目描述",
        }
        error_messages = {
            "project_name": {"required": "不能为空"},
            "project_detail": {"required": "不能为空"}
        }
        widgets = {
            "project_name": wid.TextInput(attrs={"class": "form-control"}),
            "project_detail": wid.Textarea(attrs={"class": "form-control"})
        }

引用

创建时引用

html文件

<form action="" method="post" novalidate>
    {% csrf_token %}
    {% for foo in form %}
        <div class="form-group">
            <label for="">{{ foo.label }}</label>
            {{ foo }}
            <span style="color: red">{{ foo.errors.0 }}</span>
        </div>
    {% endfor %}
    <input type="submit" value="提交" class="btn btn-default">
</form>

views.py

def project_add(request):
    """ 新增项目记录 """
    if request.method == 'POST':
        form_obj = ProjectForm(request.POST)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('/index/')
        else:
            return render(request, 'project_add.html', {'form': form_obj})
    else:
        form_obj = ProjectForm()
        return render(request, 'project_add.html', {"form": form_obj})

编辑时的用法

html文件不变。
需要在使用modelform时使用instance传递数据,进行更新。
views.py

def project_update(request, pk):
    """ 更新项目 """
    model_obj = models.Project.objects.filter(pk=pk).first()
    if request.method == 'POST':
        form_obj = ProjectForm(request.POST, instance=model_obj)
        if form_obj.is_valid():
            form_obj.save()
            return redirect('/index/')
        else:
            return render(request, 'update_project.html', {'form': form_obj})
    else:
        form_obj = ProjectForm(instance=model_obj)
        return render(request, 'update_project.html', {"form": form_obj})

路由别忘了配置pk

from django.conf.urls import url
from django.contrib import admin
from app01 import views



urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index, name='index'),
    url(r'^project_update/(?P<pk>\d+)$', views.project_update, name='project_update'),
]

自定义标签

适合一些特殊的标签,比如日期标签,下面是form设置。
法1

from django import forms
from django.forms import widgets as wid
from app01 import models

class ApiForm(forms.ModelForm):
    # 自定义标签
    api_start_time = forms.DateField(label="开始时间", widget=wid.DateInput(attrs={"class": "form-control", 'type': "date"}))
    api_stop_time = forms.DateField(label="结束时间",widget=wid.DateInput(attrs={"class": "form-control", 'type': "date"}))

    class Meta:
        model = models.API
        fields = "__all__"
        # exclude = ['project_status']  # 排除哪些字段
        # labels = {
        #     "project_name": "项目名称",
        #     "project_detail": "项目描述",
        # }
        error_messages = {
            "api_title": {"required": "不能为空"},
            "api_desc": {"required": "不能为空"}
        }
        widgets = {
            "api_title": wid.TextInput(attrs={"class": "form-control"}),
            "api_desc": wid.Textarea(attrs={"class": "form-control"})
        }

法2

from django.forms import ModelForm
from django import forms
from django.forms import widgets as wid
from app01 import models

class ApiForm(ModelForm):
    class Meta:
        model = models.API
        fields = "__all__"
    bootstrapClass_filter = ['api_start_time', 'api_stop_time']
    api_start_time= forms.DateField(label="开始时间",
                                     widget=wid.DateInput(attrs={"class": "form-control", 'type': "date"}))
    api_stop_time= forms.DateField(label="结束时间", widget=wid.DateInput(attrs={"class": "form-control", 'type': "date"}))
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            if name in self.bootstrapClass_filter:
                continue
            old_class = field.widget.attrs.get('class', "")
            field.widget.attrs['class'] = '{} form-control'.format(old_class)
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)

数据库:


class API(models.Model):
    """ 接口表 """
    api_title = models.CharField(max_length=32, verbose_name='接口名称')
    api_desc = models.CharField(max_length=128, verbose_name='接口描述')

    api_start_time = models.DateField(auto_now_add=True)
    api_stop_time = models.DateField(auto_now_add=True)
    def __str__(self):
        return self.api_title

    def xxoo(self):  # 自定义字段
        if self.case_set.count():
            a = "%s%% " % (self.case_set.filter(case_pass_status=1).count() / self.case_set.count() * 100)
            return a
        else:
            return 0
posted @ 2019-12-14 23:34  听雨危楼  阅读(240)  评论(1编辑  收藏  举报