问题
I am using django-haystack with Solr
backend in one of my projects. I have a SearchForm which inherits from FacetedSearchForm
. Now, what I am trying to do is to add an intital value to some of the fields within the Form.
from django.forms import forms
from haystack.forms import FacetedSearchForm
MySearchForm(FacetedSearchForm):
""" My basic search form
"""
field_one = forms.CharField(required=False, initial='0')
field_two = forms.CharField(required=False, initial='some_value')
previously when i was using django.forms.Form
this used to work absolutely fine. I have been digging around django code and haystack code and fond that FacetedSearchForm
extends haystack.forms.SearchForm
which extends django.forms.Forms
. So I can not see a reason why this should not work.
References:
- haystack.forms.FacetedSearchForm
- django.forms.Form
I also tried overriding the __init__
method and thought I would set the initial values there:
def __init__(self, *args. **kwargs):
data = kwargs.pop('data', None)
if data:
values = {
'field_one': (data.get('field_one', None), '0'),
'field_two': (data.get('field_two', None), 'some_value')
}
for value in values:
if not values[value][0]:
self.fields[value].initial = values[value][3]
super(MySearchForm, self).__init__(*args, **kwargs)
but in a FacetedSearchForm
there is no fields
attribute, though they provide access to base_fields
object, so I instead tried doing:
self.base_fields[value].initial = values[value][4]
which does not work either.
Strange part came when I realized that It does not raise any errors or exceptions, so I tried printing out the initial values to debug and well it does show that inital values are set.
But when the form is rendered in the template the fields does not have those initial values. The values for the fields are None for both fields in the template.
I tried checking the value using:
{{ form.field_one.value }}
{{ form.field_two.value }}
and the output is:
None
None
Have anyone ran into this issue before ? How can I have inital values show up in the template when the form is rendered ?
回答1:
As django.forms.Form
set initial data only to an unbound form setting inital is not an option here. We should rather pass the inital values as data to the build_form
method in haystack.views.FacetedSearchView
as this is where form is initialized.
Example:
MySearchView(FacetedSearchView):
def build_form(self, form_kwargs=None):
""" Overrides the build_form method to send initial data
"""
form = super(MySearchForm, self).build_form(form_kwargs)
form_data = form.data.copy() # Need to copy this as QueryDict is immutable
# Set initial data hete
form_data['field_name'] = 'fields_inital_value'
form.data = form_data
return form
来源:https://stackoverflow.com/questions/16340222/set-fields-initial-value-within-haystacks-facetedsearchform