【问题标题】:Django - How to extend a form?Django - 如何扩展表单?
【发布时间】:2011-11-10 09:14:20
【问题描述】:

我是 Django 新手。我已经安装了一个位于“python2.6/site-packages/haystack”中的外部应用程序。这个外部应用程序具有“通用表单”,但我需要添加一个不在“通用表单”中的 CSS 类。

如何在我自己的应用程序中将“forms.py”和“class FacetedModelSearchForm”从“通用表单”扩展为“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”中扩展该类的 CSS 类“myspecialcssclass”添加到字段“q”?我需要扩展的类是“FacetedSearchForm”。有什么线索吗?

【问题讨论】:

    标签: django django-forms django-haystack


    【解决方案1】:
    from haystack.forms import FacetedSearchForm
    
    class CustomSearchForm(FacetedSearchForm)
        q = forms.CharField(required=False, label='Search', widget=forms.widgets.TextInput(attrs={"class":"myspecialcssclass",}))
    

    您的自定义表单必须在您的 haystack url 中设置,例如:

    from haystack.views import SearchView
    
    urlpatterns = patterns('haystack.views',
        url(r'^$', SearchView(form_class=CustomSearchForm, results_per_page=20), name='haystack_search'),
    )
    

    另见大海捞针views and forms documentation

    【讨论】:

      【解决方案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'}))
      

      应该就是这样。

      【讨论】:

        【解决方案3】:

        表单字段小部件attrs 将html 属性映射到它们的值。在子类__init__ 函数中覆盖这些属性以安全地修改该字段。

        class MyForm(FacedSearchForm):
            def __init__(self, *args, **kwargs):
                super(MyForm, self).__init__(*args, **kwargs)
                self.fields['q'].widget.attrs['class'] = 'myspecialcssclass'
        

        【讨论】:

          猜你喜欢
          • 2011-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-06-10
          • 2010-12-30
          • 2016-08-16
          • 2020-12-14
          • 1970-01-01
          相关资源
          最近更新 更多