Django - 设置过滤器字段标签或verbose_name

时间:2015-07-28 20:11:51

标签: django django-filter

我正在使用django-tables2显示数据表。

对于过滤我正在使用此处的解决方案:

How do I filter tables with Django generic views?

我的问题只是我无法为过滤器表单设置标签。对谷歌来说这也是不可能的,因为单词“django,form,filter,label”非常一般:(

我的过滤器类:

import django_filters as filters
from models import Sale

class SaleFilter(filters.FilterSet):
    class Meta:
        model = Sale
        fields = ['CompanyProductID', 'CompanySellerID', 'CompanyRegisterID']
        labels = {
            'CompanyProductID': 'Article',
            'CompanySellerID': 'Seller',
            'CompanyRegisterID': 'Cash register'
        }     #THIS IS NOT WORKING

4 个答案:

答案 0 :(得分:3)

要设置自定义标签,您可以这样做。不确定它是否是新功能。

import django_filters as filters
from models import Sale

class SaleFilter(filters.FilterSet):
    CompanyProdutID = filters.CharFilter(label='Article')
    CompanySellerID = filters.CharFilter(label='Seller')
    CompanyRegisterID = filters.CharFilter(label='Cash register')

    class Meta:
        model = Sale
        fields = ['CompanyProductID', 'CompanySellerID', 'CompanyRegisterID']

为每个字段使用所需的过滤器。

docs

注意:

出于某种原因

import django_filters as filters
filters.CharField(...)

不适合我。我必须像这样使用它:

from django_filters import CharFilter
CharFilter(...)

答案 1 :(得分:2)

class ProductFilter(django_filters.FilterSet):
    class Meta:
        model = Product
        fields = ['manufacturer']

    def __init__(self, *args, **kwargs):
        super(ProductFilter, self).__init__(*args, **kwargs)
        self.filters['manufacturer'].extra.update(
            {'empty_label': 'All Manufacturers'})

答案 2 :(得分:0)

上一个答案将重复过滤器字段。这是操作方法:

    def __init__(self, *args, **kwargs):
       super(SaleFilter, self).__init__(*args, **kwargs)
       self.filters['CompanyProductID'].label="Article"
       self.filters['CompanySellerID'].label="Seller"
       self.filters['CompanyRegisterID'].label="Cash register"

答案 3 :(得分:0)

我实际上认为操作人员正在询问“标签名称”。不是字段名称。为此,只需执行以下操作即可。

class Name_of_Filter(django_filters.FilterSet):

#example of how to set custom labels
your_field_name = django_filters.WhateverFilterYouWantHere(label='Whatever you want')

class Meta:
    model = Your_Model_Here
    fields = ['your_field_name'] 
    #could also do something like '__all__' to get all the fields for that table just have to refer to your models to get the field name