我想使用Django构建一个简单的视图。将会有一个客户站点的下拉列表,然后,在选择一个客户站点后,该视图将填充先前所选客户的竞争对手的下拉列表。我的麻烦在于第二部分:当我从第一个下拉列表中选择客户时,按“选择”键。页面重新加载,但竞争对手的下拉列表是空的:
我调试了代码,并为竞争对手下拉列表返回了值,它们是正确的。 我有这个单一的观点:
def index_unify_brands(request):
class CustomerSiteDropDown(forms.Form):
customer_site_id = forms.ChoiceField(Site.objects.filter(site_type='customer').exclude(
crawl_groups='').values_list('id', 'site_name').order_by('site_name'), required=True)
class OptionsForm(forms.Form):
competitors_site_ids = forms.ChoiceField()
def populate_competitors_in_dropdown(self,customer_site_id):
competitors_ids = get_competitors_positions(customer_site_id)[
customer_site_id].keys() # todo: if no competitors
print competitors_ids
competitors_for_dropdown = Site.objects.filter(id__in=competitors_ids).exclude(crawl_groups='') \
.values_list('id', 'site_name').order_by('site_name')
print competitors_for_dropdown
self.competitors_site_ids = forms.ChoiceField(competitors_for_dropdown, required=True)
if request.method == 'POST':
# received request for a specific customer site id
customer_dropdown_form = CustomerSiteDropDown(request.POST)
options_form = OptionsForm(request.POST)
options_form.populate_competitors_in_dropdown(int(request.POST['customer_site_id']))
if customer_dropdown_form.is_valid():
return render_to_response('manage/unify_brands/unify_brands.html',
{'customer_dropdown_form': customer_dropdown_form,
'options_form': options_form},
context_instance=RequestContext(request)
)
else:
customer_dropdown_form = CustomerSiteDropDown()
return render_to_response('manage/unify_brands/unify_brands.html',
{'customer_dropdown_form': customer_dropdown_form},
context_instance=RequestContext(request))
似乎当我实例化OptionsForm
对象时,options_form.populate_competitors_in_dropdown(....)
方法不会更改此对象内由competitors_site_ids
变量表示的下拉列表。
知道我在这里做错了吗?
答案 0 :(得分:0)
在您的表单中,self.competitors_site_ids
并非任何相关内容。您需要分配到self.fields['competitors_site_ids']
。
此代码也应该在__init__
中,而不是单独的方法。