本文介绍了如何在上下文处理器(Django 1.3)中使用包含ChoiceField的HayStack表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
class BasicSearchForm(SearchForm):
category_choices = Category.objects.all()
category_tuples = tuple([(c.id,c.name)for category in category_choices])
category = forms.ChoiceField(choices = category_tuples,required = False )
def search(self):
sqs = super(BasicSearchForm,self).search()
如果self.cleaned_data ['category']:
如果self.cleaned_data ['category']!=*:
sqs = sqs.filter(category__id = self.cleaned_data ['category'])
返回sqs
然后我有一个这样的上下文处理器:
$ search $($)
basic_search = BasicSearchForm()
return {'basic_search':basic_search}
由于某些原因,创建一个新的类别对象(通过Django管理员,并保存它)将不会更新我的类型元组选择窗体直到我重新启动Apache。
有谁知道什么可以造成这个
提前感谢
解决方案
发布,处理您的情况:
您希望在表单启动时设置选项:
class BasicSearchForm(SearchForm):
def __init __(self,* args,** kwargs):
super(BasicSearchForm,self).__ init __(* args,** kwargs)
category_choices = Category.objects.all()
category_tuples = tuple([(c.id,c.name)for category in category_choices])
self.fields ['category'] = forms.ChoiceField(choices =
sqs = super(BasicSearchForm,self).search()
如果self.cleaned_data ['类别']:
如果self.cleaned_data ['category']!=*:
sqs = sqs.filter(category__id = self.cleaned_data ['category'])
返回sqs
I have a pretty simple Haystack form that looks just like this:
class BasicSearchForm(SearchForm):
category_choices = Category.objects.all()
category_tuples = tuple([(c.id, c.name) for c in category_choices])
category = forms.ChoiceField(choices=category_tuples, required=False)
def search(self):
sqs = super(BasicSearchForm, self).search()
if self.cleaned_data['category']:
if self.cleaned_data['category'] != "*":
sqs = sqs.filter(category__id=self.cleaned_data['category'])
return sqs
I then have a context processor just like this:
def search_form(request):
basic_search = BasicSearchForm()
return { 'basic_search': basic_search }
For some reason, creating a new category object (via the Django admin, and saving it) will not update my category tuple used in the ChoiceField of the form until I restart Apache.
Does anyone know what could be causing this?
Thanks in advance!
解决方案
Take a look at this blog post, it deals with your situation:
You want to set the choices whenever the form is initiated:
class BasicSearchForm(SearchForm):
def __init__(self, *args, **kwargs):
super(BasicSearchForm,self).__init__(*args,**kwargs)
category_choices = Category.objects.all()
category_tuples = tuple([(c.id, c.name) for c in category_choices])
self.fields['category'] = forms.ChoiceField(choices=category_tuples, required=False)
def search(self):
sqs = super(BasicSearchForm, self).search()
if self.cleaned_data['category']:
if self.cleaned_data['category'] != "*":
sqs = sqs.filter(category__id=self.cleaned_data['category'])
return sqs
这篇关于如何在上下文处理器(Django 1.3)中使用包含ChoiceField的HayStack表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!