0
這是一個非基於模型的形式:在一個Django表單集在後返回,所有形式展示各個領域的變化,即使沒有具有
from django import forms
class MeasureForm(forms.Form):
name = forms.CharField(max_length=15)
description = forms.CharField(max_length=100)
datatype = forms.CharField(max_length=20)
uom = forms.Char
從非基於模型的視圖填充的:
def define_measures(request):
measureformset = formset_factory(MeasureForm, extra=2)
if request.method == 'POST': # If the form has been submitted...
formset = measureformset(request.POST) # A form bound to the POST data
if formset.is_valid(): # All validation rules pass
for form in formset:
print form.changed_data
return HttpResponseRedirect('/viscas/measures') # Redirect after POST
else:
measures = cass.get_all_measures()
list_dict =[]
for measure in measures:
list_dict.append({'name': measure.name, 'description': measure.description, 'datatype': measure.datatype, 'uom': measure.uom})
formset = measureformset(initial=list_dict)
return render(request, 'viscas/measure.html', {
'formset': formset,
})
正在模板渲染「手動」:
{% extends "base.html" %}
{% block content %}
<body>
<div class="container">
<form action="{% url 'viscas:define_measures' %}" method="post">
{% csrf_token %}
<div>
<table class="table table-hover" name="poi" id="tagTable">
<thead>
<tr>
<th>UOM</th>
<th>Description</th>
<th>Datatype</th>
<th>UOM</th>
</tr>
</thead>
{% for form in formset %}
<tr>
<td>{{ form.name }}</td>
<td>{{ form.description }}</td>
<td>{{ form.datatype }}</td>
<td>{{ form.uom }}</td>
{% if form.errors %}
<tr>
<td>{{ form.errors }}</td>
</tr>{% endif %}
</tr>
{% endfor %}
</table>
{{ formset.management_form }}
</div>
<p></p><input type="submit" value="Submit"/></p>
</form>
</div>
</body>
{% endblock %}
該頁面顯示漂亮,把我是否張貼有沒有變化WHA即使在網頁上,每個表格都顯示所有字段已更改(除了兩個額外的空白)。
從這個代碼:
if request.method == 'POST': # If the form has been submitted...
formset = measureformset(request.POST) # A form bound to the POST data
if formset.is_valid(): # All validation rules pass
for form in formset:
print form.changed_data
我得到這樣的輸出:
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
['name', 'description', 'datatype', 'uom']
[]
[]