我是Django的新手。我已经在“python2.6 / site-packages / haystack”中安装了一个外部应用程序。这个外部应用程序有“通用表单”,但我需要添加一个不是“通用表单”的CSS类。
如何在我自己的应用程序中将“forms.py”“class FacetedModelSearchForm”从“generic form”扩展到“forms.py”?
以下是“通用表单”中的代码
class SearchForm(forms.Form):
q = forms.CharField(required=False, label=_('Search'))
def __init__(self, *args, **kwargs):
self.searchqueryset = kwargs.pop('searchqueryset', None)
self.load_all = kwargs.pop('load_all', False)
if self.searchqueryset is None:
self.searchqueryset = SearchQuerySet()
super(SearchForm, self).__init__(*args, **kwargs)
def no_query_found(self):
"""
Determines the behavior when no query was found.
By default, no results are returned (``EmptySearchQuerySet``).
Should you want to show all results, override this method in your
own ``SearchForm`` subclass and do ``return self.searchqueryset.all()``.
"""
return EmptySearchQuerySet()
def search(self):
if not self.is_valid():
return self.no_query_found()
if not self.cleaned_data.get('q'):
return self.no_query_found()
sqs = self.searchqueryset.auto_query(self.cleaned_data['q'])
if self.load_all:
sqs = sqs.load_all()
return sqs
def get_suggestion(self):
if not self.is_valid():
return None
return self.searchqueryset.spelling_suggestion(self.cleaned_data['q'])
class FacetedSearchForm(SearchForm):
def __init__(self, *args, **kwargs):
self.selected_facets = kwargs.pop("selected_facets", [])
super(FacetedSearchForm, self).__init__(*args, **kwargs)
def search(self):
sqs = super(FacetedSearchForm, self).search()
# We need to process each facet to ensure that the field name and the
# value are quoted correctly and separately:
for facet in self.selected_facets:
if ":" not in facet:
continue
field, value = facet.split(":", 1)
if value:
sqs = sqs.narrow(u'%s:"%s"' % (field, sqs.query.clean(value)))
return sqs
如何在我的应用程序“forms.py”中向字段“q”添加扩展此类的CSS类“myspecialcssclass”?我需要扩展的类是“FacetedSearchForm”。有线索吗?
答案 0 :(得分:3)
from haystack.forms import FacetedSearchForm
class CustomSearchForm(FacetedSearchForm)
q = forms.CharField(required=False, label='Search', widget=forms.widgets.TextInput(attrs={"class":"myspecialcssclass",}))
您的自定义表单必须在您的草垛网址中设置,例如:
from haystack.views import SearchView
urlpatterns = patterns('haystack.views',
url(r'^$', SearchView(form_class=CustomSearchForm, results_per_page=20), name='haystack_search'),
)
另请参阅haystack views and forms documentation
答案 1 :(得分:2)
我想这个:
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#customizing-widget-instances
可能有所帮助。
基本上,您需要子类FacetedSearchForm
并为您的小部件
class MyForm(FacetedSearchForm):
q = forms.CharField(
required=False,
label='Search',
widget=forms.TextInput(attrs={'class':'myspecialcssclass'}))
那应该是它。
答案 2 :(得分:1)
表单字段小部件attrs
将html属性映射到其值。在子类__init__
函数中重写这些属性以安全地修改字段。
class MyForm(FacedSearchForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['q'].widget.attrs['class'] = 'myspecialcssclass'