user3062149
user3062149

Reputation: 4443

Setting label_suffix for a Django model formset

I have a Product model that I use to create ProductFormSet. How do I specify the label_suffix to be something other than the default colon? I want it to be blank. Solutions I've seen only seem to apply when initiating a form - here.

ProductFormSet = modelformset_factory(Product, exclude=('abc',))    
products = Product.objects.order_by('product_name')
pformset = ProductFormSet(queryset=products)

Upvotes: 6

Views: 2261

Answers (2)

Jaroslav Gorjatsev
Jaroslav Gorjatsev

Reputation: 79

Another way is to create custom tag:

@register.filter("set_label_suffix")
def set_label_suffix(field, suffix=''):
    field.field.label_suffix = suffix
    return field

And then use in the template (also using widget_tweaks in this example):

{% for field in channel_change_form %}
   <div class="form-group">
       {{ field.errors }}
       {{ field|add_label_class:"col-form-label"}}
       {{ field|set_label_suffix|add_class:"form-control" }}
   </div>
...

Upvotes: 1

Alasdair
Alasdair

Reputation: 308779

In Django 1.9+, you can use the form_kwargs option.

ProductFormSet = modelformset_factory(Product, exclude=('abc',))    
products = Product.objects.order_by('product_name')
pformset = ProductFormSet(queryset=products, form_kwargs={'label_suffix': ''})

In earlier Django versions, you could define a ProductForm class that sets the label_suffix to blank in the __init__ method, and then pass that form class to modelformset_factory.

class ProductForm(forms.ModelForm):
    ...
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs)
        self.label_suffix = ''

ProductFormSet = modelformset_factory(Product, form=ProductForm, exclude=('abc',))    

Upvotes: 6

Related Questions