看到Django-forms写的好的一篇文章:[(5)Django框架学习-Forms篇]
- 定义forms
# coding:utf-8
from django import forms
from devops.models import PCI,PCI_RELEASE,ONLINE_VERSION,PCI_BUILDS
from django.forms.extras.widgets import SelectDateWidget
class PCIForm(forms.ModelForm):
class Meta:
model = PCI
fields = ["pro", "job_name","pro_scm", "last_build_number", "last_build_result", "last_build_url", "last_update_time"]
......
class OnlineVersionFeedbackForm(forms.ModelForm):
class Meta:
model = ONLINE_VERSION
widgets = {'upgrade_date': SelectDateWidget()} #日历选择框
fields = ["pro", "pci_release", "release_name", "IM_plan", "upgrade_date", "upgrade_result",
"upgrade_fail_desc", "upgrade_user"]
def __init__(self, *args, **kwargs):
super(forms.ModelForm, self).__init__(*args, **kwargs)
self.fields['pro'].widget.attrs['readonly'] = True #只读
self.fields['pci_release'].widget.attrs['readonly'] = True
self.fields['release_name'].widget.attrs['readonly'] = True
- 界面使用
通过使用 form.字段来使用
<form action="" method="post" class="form-horizontal" id="pciReleaseForm" enctype="multipart/form-data" >
{% csrf_token %}
<h3>{% trans 'Basic' %}</h3>
{% bootstrap_field form.pro layout="horizontal" %}
{% bootstrap_field form.pci_release layout="horizontal" %}
{% bootstrap_field form.release_name layout="horizontal" %}
<div class="hr-line-dashed"></div>
{% bootstrap_field form.upgrade_date layout="horizontal" %}
{% bootstrap_field form.upgrade_result layout="horizontal" %}
{% bootstrap_field form.upgrade_fail_desc layout="horizontal" %}
{% bootstrap_field form.upgrade_user layout="horizontal" %}
<div class="hr-line-dashed"></div>
<div class="form-group">
<div class="col-sm-4 col-sm-offset-2">
<button class="btn btn-default" type="reset"> {% trans 'Reset' %}</button>
<button id="submit_button" class="btn btn-primary" type="submit">{% trans 'Submit' %}</button>
</div>
</div>
</form>
- views 中对form进行逻辑上的验证
def form_valid(self, form):
- 最终效果