python(07)实践Django-forms

看到Django-forms写的好的一篇文章:[(5)Django框架学习-Forms篇]

  1. 定义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
  1. 界面使用
    通过使用 form.字段来使用
{% csrf_token %}

{% trans 'Basic' %}

{% bootstrap_field form.pro layout="horizontal" %} {% bootstrap_field form.pci_release layout="horizontal" %} {% bootstrap_field form.release_name layout="horizontal" %}
{% 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" %}
  1. views 中对form进行逻辑上的验证
 def form_valid(self, form):
  1. 最终效果
python(07)实践Django-forms_第1张图片
Paste_Image.png

你可能感兴趣的:(python(07)实践Django-forms)