How can I use a HayStack form that contains a ChoiceField within a Context Processor(Django 1.3)?

限于喜欢 提交于 2019-12-13 04:25:36

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/5862666/how-can-i-use-a-haystack-form-that-contains-a-choicefield-within-a-context-proce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!