我有一个似乎永远不会验证的表单。表单只有三个下拉框。呈现表单时,所有框都填充了值并且第一个被选中,因此无论如何,用户都无法提交错误值,但form.is_valid()始终返回false。请帮忙!
表格
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)
视图
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)
答案 0 :(得分:2)
您已覆盖表单__init__
方法的签名,因此第一个位置参数为sets
。但是,当您实例化它时,您将request.POST
作为第一个位置参数传递 - 因此表单永远不会获取任何数据,因此不会验证。
请勿更改__init__
的签名。实际上,您已正确设置所有内容,因此您无需:只需从方法定义中删除sets=None
,它就可以正常工作。