0
我有一個似乎永遠不會驗證的表單。該表格只是三個下拉框。當表單呈現時,所有框都填充了值,第一個被選中,所以無論如何,用戶都不能提交錯誤的值,但form.is_valid()總是返回false。請幫忙!Django表單驗證問題
形式
CLUSTER_TYPES = (
('ST', 'State'),
('CNT', 'County'),
('FCD', 'Congressional District'),
('GCC', 'Circle Clustering'),
);
MAP_VIEWS = (
('1', 'Single Map'),
('2', 'Two Maps'),
('4', 'Four Maps'),
);
class ViewDataForm (forms.Form):
def __init__ (self, sets = None, *args, **kwargs):
sets = kwargs.pop ('data_sets')
super (ViewDataForm, self).__init__ (*args, **kwargs)
processed_sets = []
for ds in sets:
processed_sets.append ((ds.id, ds.name))
self.fields['data_sets'] = forms.ChoiceField (label='Data Set', choices = processed_sets)
self.fields['clustering'] = forms.ChoiceField (label = 'Clustering',
choices = CLUSTER_TYPES)
self.fields['map_view'] = forms.ChoiceField (label = 'Map View', choices = MAP_VIEWS)
您已覆蓋窗體的__init__
方法的簽名,使得第一位置參數是sets
視圖
def main_view (request):
# We will get a list of the data sets for this user
sets = DataSet.objects.filter (owner = request.user)
# Create the GeoJSON string object to potentially populate
json = ''
# Get a default map view
mapView = MapView.objects.filter (state = 'Ohio', mapCount = 1)
mapView = mapView[0]
# Act based on the request type
if request.method == 'POST':
form = ViewDataForm (request.POST, request.FILES, data_sets = sets)
v = form.is_valid()
if form.is_valid():
# Get the data set
ds = DataSet.objects.filter (id = int (form.cleaned_data['data_set']))
ds = ds[0]
# Get the county data point classifications
qs_county = DataPointClassification.objects.filter (dataset = ds,
division = form.cleaned_data['clustering'])
# Build the GeoJSON object (a feature collection)
json = ''
json += '{"type": "FeatureCollection", "features": ['
index = 0
for county in qs_county:
if index > 0:
json += ','
json += '{"type": "feature", "geometry" : '
json += county.boundary.geom_poly.geojson
json += ', "properties": {"aggData": "' + str (county.aggData) + '"}'
json += '}'
index += 1
json += ']}'
mapView = MapView.objects.filter (state = 'Ohio', mapCount = 1)
mapView = mv[0]
else:
form = ViewDataForm (data_sets = sets)
# Render the response
c = RequestContext (request,
{
'form': form,
'mapView_longitude': mapView.centerLongitude,
'mapView_latitude': mapView.centerLatitude,
'mapView_zoomLevel': mapView.zoomLevel,
'geojson': json,
'valid_was_it': v
})
return render_to_response ('main.html', c)
如果我一直在關注,'sets = None'首先不會存在。非常感謝。 – Nik 2011-03-28 18:11:29