Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - set filter field label or verbose_name

I'm displaying a table of data using django-tables2.

For filtering I'm using the solution from here:

How do I filter tables with Django generic views?

My problem is only that I can't set the labels for the filter form. This is also imposible to google as words "django, form, filter, label" are quite general :(

My filter class:

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
like image 993
user568021 Avatar asked Jul 28 '15 20:07

user568021


3 Answers

To set custom labels you can do it this way. Not sure if it is a new functionality.

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']

Use the filter that you want for each field.

docs

Note:

for some reason

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

is not working for me. I have to use it like this:

from django_filters import CharFilter
CharFilter(...)
like image 84
Carlos Goce Avatar answered Dec 15 '22 03:12

Carlos Goce


Previous answer will duplicate the filter fields. Here is how to do it:

    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"
like image 36
openHBP Avatar answered Dec 15 '22 03:12

openHBP


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'})
like image 32
madzohan Avatar answered Dec 15 '22 04:12

madzohan