Django - 如何扩展表单?

发布于 2024-12-15 06:41:21 字数 2249 浏览 4 评论 0原文

我是姜戈的新手。我已经安装了一个位于“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

如何将 CSS 类“myspecialcssclass”添加到字段“q”中,在我的应用程序“forms.py”中扩展此类?我需要扩展的类是“FacetedSearchForm”。有什么线索吗?

I'm new to Django. I have installed an external App that is in "python2.6/site-packages/haystack". This external App have "generic forms" but I need to add a CSS class that is not in the "generic form".

How can I extend the "forms.py" the "class FacetedModelSearchForm" from the "generic form" to "forms.py" in my own App?

Here is the code from the "generic form"

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

How can I add to the field "q" the CSS class "myspecialcssclass" extending this class in my App "forms.py"? The class that I need to extend is the "FacetedSearchForm". Any clues?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

找个人就嫁了吧 2024-12-22 06:41:21
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'^

另请参阅 haystack 视图和表单文档

, SearchView(form_class=CustomSearchForm, results_per_page=20), name='haystack_search'), )

另请参阅 haystack 视图和表单文档

from haystack.forms import FacetedSearchForm

class CustomSearchForm(FacetedSearchForm)
    q = forms.CharField(required=False, label='Search', widget=forms.widgets.TextInput(attrs={"class":"myspecialcssclass",}))

your custom form must be set in your haystack urls e.g:

from haystack.views import SearchView

urlpatterns = patterns('haystack.views',
    url(r'^

Also see the haystack views and forms documentation

, SearchView(form_class=CustomSearchForm, results_per_page=20), name='haystack_search'), )

Also see the haystack views and forms documentation

诠释孤独 2024-12-22 06:41:21

我认为:

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'}))

,这应该就是这样。

I think this:

https://docs.djangoproject.com/en/dev/ref/forms/widgets/#customizing-widget-instances

might help.

Basically, you need to subclass FacetedSearchForm and add an argument to you widget

class MyForm(FacetedSearchForm):
    q = forms.CharField(
            required=False,
            label='Search',
            widget=forms.TextInput(attrs={'class':'myspecialcssclass'}))

And that should be it.

岁月苍老的讽刺 2024-12-22 06:41:21

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

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

The form field widget attrs maps html attributes to their values. Override these attributes in a subclasses __init__ function to safely modify the field.

class MyForm(FacedSearchForm):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['q'].widget.attrs['class'] = 'myspecialcssclass'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文