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:
http://blog.e-shell.org/130
BUT, there is a problem with that.
Doing it that way, the list of choices
for each field will be generated on
startup time (when you launch the
django development server or apache or
lighttpd or nginx or whatever you are
using). That means that if you add a
new user to the maintainers group, it
will not appear in the maintainer
field until you restart your server!
To avoid that, we will need to add the
current available choices before using
the form, overwriting the default list
of choices:
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