2013-04-03 80 views
2

我正在擴展ListFilter以在Django 1.4中爲Django Admin創建自定義ListFilter,但django自動將我的查詢字符串參數轉換爲e = 1。有什麼辦法可以告訴Django管理員允許某些參數;而不是將它們轉換爲e = 1。在django中創建自定義列表過濾器

這裏是我的自定義ListFilter:

class DateRangeListFilter(ListFilter): 
    """ Custom Date Range Filter using Jquery UI for date-picker """ 
    title = _('date range') 
    template = 'admin/filter_date.html' 

    parameters = ['class_after', 'class_before'] 
    parameter_friendly_names = {parameters[0]: 'Class After', parameters[1]: 'Class Before'} 
    parameter_values = {} 
    parameter_name = parameters[0] 
    used_parameters = {parameters[0]: '', parameters[1]: ''} 

    def __init__(self, request, params, model, model_admin): 
     super(ListFilter, self).__init__() 

     for parameter in self.parameters: 
      value = request.GET.get(parameter, None) 
      if value: 
       self.parameter_values[parameter] = value 

     self.lookup_choices = list(self.lookups()) 

    def has_output(self): 
     return len(self.lookup_choices) > 0 

    def lookups(self, *args): 
     lookup_list = [] 
     for key in self.parameters: 
      lookup_list.append((key, self.parameter_friendly_names[key])) 
     return lookup_list 

    def expected_parameters(self): 
     return self.parameters 

    def queryset(self, request, queryset): 
     return queryset 

    def choices(self, cl): 
     for lookup, title in self.lookup_choices: 
      param_name = title 
      replace_text = 'gte_icdate' if title == self.parameters[0] else 'lte_icdate' 
      value = self.parameter_values[lookup] if self.parameter_values.has_key(lookup) else '' 
      yield { 
       'param_name': param_name, 
       'selected': True if lookup is not None else False, 
       'query_string': cl.get_query_string({param_name: replace_text, }, []), 
       'value': value, 
       'display': title, 
       'replace_text': replace_text, 
       } 

回答

-1

Django是太不可思議有時。幾乎肯定有一個正確的方法來做到這一點,我正在做的可能不是它。但我修改了我的init函數以從字典中刪除我的特殊參數;因此django管理員忽略它。

def __init__(self, request, params, model, model_admin): 
    super(ListFilter, self).__init__() 

    for param_key in self.parameters: 
     if param_key in params.keys(): 
      self.parameter_values[param_key] = params[param_key] 
      del params[param_key] # This is the anti-magic line 
     else: 
      self.parameter_values[param_key] = '' 

    self.lookup_choices = list(self.lookups()) 
-1

我見過,確實發生:看來你需要離開一個「乾淨」的參數設置到視圖。 我見過pop()被用作更高效的替代品:

def __init__(self, request, params, model, model_admin): 
    super(ListFilter, self).__init__() 

    for param_key in self.parameters: 
     self.parameter_values[param_key] = params.pop(param_key,'') 

    self.lookup_choices = list(self.lookups()) 
相關問題