我已经搜索了很多这个答案,我相信这是一个非常基本的东西,我很想念。我想在django中将参数传递给动态表单。表单根据传递给它的值动态填充ChoiceField,但是我得到了一个关键错误,因为location_choice'当我提交表格时。
表单传递一个location_choice(实际上是一个组),然后根据该过滤器选择一个相关位置列表,并使用列为每个位置的PK的值填充下拉列表。我不能做的就是提交该表单并将该值传递回后续视图。当我收到密钥错误时,我无法传回任何数据
我花了好几个小时试图理解我在这里做错了什么,包括阅读这篇文章,这很有帮助,但我仍然遗漏了一些东西:
https://jacobian.org/writing/dynamic-form-generation/
views.py
def test_search(request):
form = search_criteria(request.POST or None, location_choice="Group A")
return render(request, 'utilisation/util_search_day_theatre.html', { 'form': form })
forms.py
class search_criteria(forms.Form):
start_date = forms.DateField(label='Start Date', required = False, input_formats=['%d/%m/%y', '%d/%m/%Y'], initial="1/1/16")
end_date = forms.DateField(label='End Date', required = False, input_formats=['%d/%m/%y', '%d/%m/%Y'], initial='1/5/16')
dayofweek_dataset = dayofweek.objects.all().values_list()
dayofweek_choice = forms.ChoiceField(required=True, label='Choose a Day of the Week:', choices= dayofweek_dataset, initial=2)
def __init__(self, *args,**kwargs):
self.location_choice= kwargs.pop('location_choice')
super(search_criteria,self).__init__(*args,**kwargs)
location_query = locationslist.objects.filter(location_group__exact=self.location_choice).values_list('id','location').order_by('id').distinct()
self.fields['location_choice'] = forms.ChoiceField(required=True, label='Choose a Location', choices= location_query)
def location_choice(self):
yield (self.fields[location_choice].label, value)
消息来源告诉我,ChoiceField正如我所料,填充下拉菜单,并为特定组中的每个位置提供正确的PK。
当我提交表单时,我收到了一个KeyError:
Traceback Switch to copy-and-paste view
/Library/Python/2.7/site-packages/django/core/handlers/exception.py in inner
response = get_response(request) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/core/handlers/base.py in _get_response
response = self.process_exception_by_middleware(e, request) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/core/handlers/base.py in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/Users/TD3/django/tass/utilisation/views.py in generic_render
form_data = search_criteria(request.POST) ...
▶ Local vars
/Users/TD3/django/tass/utilisation/forms.py in __init__
self.location_choice= kwargs.pop('location_choice') ...
▶ Local vars
views.generic_render中唯一存在的是表单验证步骤,其中HttpResponse为'成功'如果表单数据有效。一旦我能够弄清楚如何将数据输入它,我将构建该视图,因为它将使用表单数据执行许多其他操作。我目前作为几个硬编码视图工作,每个location_group都有一个单独的视图。我只是想让它成为pythonic(尽我所能)并拥有通用搜索视图和通用显示视图
def generic_render(request):
if request.method == 'POST':
form_data = search_criteria(request.POST)
if form_data.is_valid():
return HttpResponse("Success")
else:
return HttpResponse("Form data not valid")
答案 0 :(得分:0)
我不明白为什么你在这里使用两种观点。但是,既然如此,您需要记住将location_choice
参数传递给两者中的表单。
form_data = search_criteria(request.POST, location_choice="Group A")
(另请注意我在评论中提到的观点:您的表单方法location_choice
正被同名属性覆盖。无论如何,我怀疑您需要这种方法。)