簡體   English   中英

Django Admin中的自定義過濾器返回SuspiciousOperation

[英]Custom Filter in Django Admin returns SuspiciousOperation

我正在嘗試實現此代碼段的新版本,使其與Django 1.4和1.5兼容

有了一些改進,下面的代碼幾乎可以正常工作,除了Django返回給我一個SuspiciousOperation錯誤。 我知道如何破解它,但是我不希望接觸Django的核心。 如果您有任何建議,歡迎您:

這是我的過濾器:

class RelatedNullFilterSpec(FieldListFilter):
    def __init__(self, field, request, params, model, model_admin, field_path):
        field_root, field_name = field_path.rsplit('__', 1)
        self.lookup_title = field.verbose_name
        self.title = self.lookup_title
        self.null_lookup_kwarg = '%s__isnull' % field_root
        self.null_lookup_val = request.GET.get(self.null_lookup_kwarg, None)
        self.lookup_kwarg = '%s__exact' % (field_path)
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
        if isinstance(field, models.fields.BooleanField):
            self.lookup_choices = (
                # (None, _('All')),
                ('1', _('Yes')),
                ('0', _('No')))
        else:
            self.lookup_choices = field.get_choices(include_blank=False)
        super(RelatedNullFilterSpec, self).__init__(field, request, params, model, model_admin, field_path)

    def expected_parameters(self):
        return [self.lookup_kwarg, self.null_lookup_kwarg]

    def choices(self, cl):
        yield {'selected': self.lookup_val is None and self.null_lookup_val is None,
               'query_string': cl.get_query_string({}, [self.lookup_kwarg,self.null_lookup_kwarg]),
               'display': _('All')}
        yield {'selected': self.lookup_val is None and self.null_lookup_val=="True",
               'query_string': cl.get_query_string({self.null_lookup_kwarg:True},[self.lookup_kwarg]),
               'display': _('Null')}
        yield {'selected': self.lookup_val is None and self.null_lookup_val=="False",
               'query_string': cl.get_query_string({self.null_lookup_kwarg:False},[self.lookup_kwarg]),
               'display': _('Not Null')}
        for pk_val, val in self.lookup_choices:
            yield {'selected': self.lookup_val == smart_unicode(pk_val),
                   'query_string': cl.get_query_string({self.lookup_kwarg: pk_val},[self.null_lookup_kwarg]),
                   'display': val}

然后在我的管理員中,我有以下內容:

list_filter = ('time_added', 'time_modified', ('model1__model2__property', RelatedNullFilterSpec),)

而且我總是從Django BaseModelAdmin類的lookup_allowed方法中得到此錯誤...

在django.db.models.options中,我可以實現一個hack來覆蓋或擴展self.related_fkey_lookups但是我覺得有點太過分了。

編輯:請注意,以下幾乎標准的過濾器也返回相同的錯誤:( ('venue__eat_venue', BooleanFieldListFilter)

通常,我的目標是希望有一個過濾器,該過濾器允許我根據是否存在與model2相關的字段(Null / Not-Null)和屬性值(如果存在與model2相關的字段)對對象進行排序)。 這將非常方便,我認為也不太具體。

最后,是的,當我不為我的model1__model2__property請求此自定義過濾器時,一切正常:-)

這似乎是Django中的錯誤,當您為過濾器路徑(元組的第一個元素)加上雙下划線時...在您的情況下為'model1__model2__property'

注意:現在已在Django 1.7中修復

此處有更多詳細信息: https : //code.djangoproject.com/ticket/19182

這是相當難看,但到目前為止,我發現的唯一的解決方法是這樣固定和重寫的方法粘貼到ModelAdmin要使用list_filter

def lookup_allowed(self, lookup, value):
    """
    Copy and pasted from ModelAdmin to fix bug in Django
    https://code.djangoproject.com/ticket/19182
    """
    from django.db.models.constants import LOOKUP_SEP
    from django.db.models.sql.constants import QUERY_TERMS
    from django.contrib.admin import FieldListFilter
    from django.contrib.admin import widgets

    model = self.model
    # Check FKey lookups that are allowed, so that popups produced by
    # ForeignKeyRawIdWidget, on the basis of ForeignKey.limit_choices_to,
    # are allowed to work.
    for l in model._meta.related_fkey_lookups:
        for k, v in widgets.url_params_from_lookup_dict(l).items():
            if k == lookup and v == value:
                return True

    parts = lookup.split(LOOKUP_SEP)

    # Last term in lookup is a query term (__exact, __startswith etc)
    # This term can be ignored.
    if len(parts) > 1 and parts[-1] in QUERY_TERMS:
        parts.pop()

    # Special case -- foo__id__exact and foo__id queries are implied
    # if foo has been specificially included in the lookup list; so
    # drop __id if it is the last part. However, first we need to find
    # the pk attribute name.
    rel_name = None
    for part in parts[:-1]:
        try:
            field, _, _, _ = model._meta.get_field_by_name(part)
        except FieldDoesNotExist:
            # Lookups on non-existants fields are ok, since they're ignored
            # later.
            return True
        if hasattr(field, 'rel'):
            model = field.rel.to
            rel_name = field.rel.get_related_field().name
        elif isinstance(field, RelatedObject):
            model = field.model
            rel_name = model._meta.pk.name
        else:
            rel_name = None
    if rel_name and len(parts) > 1 and parts[-1] == rel_name:
        parts.pop()

    if len(parts) == 1:
        return True
    clean_lookup = LOOKUP_SEP.join(parts)
    // FIX BEGINS:
    valid_lookups = [self.date_hierarchy]
    for filter_item in self.list_filter:
        if callable(filter_item):
            valid_lookups.append(filter_item.parameter_name)
        elif isinstance(filter_item, (list, tuple)):
            valid_lookups.append(filter_item[0])
        else:
            valid_lookups.append(filter_item)
    return clean_lookup in valid_lookups

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM