Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass extra kwargs to form in django modelformset factory?

How can i pass extra kwargs to django modelform in modelformset factory

I want for example, disable all form fields in detail view.

forms.py:

class ConceptForm(forms.ModelForm):

  class Meta:
    model = app_models.Concept
    fields = '__all__'

  def __init__(self, *args, **kwargs):

    self.action = kwargs.pop('action', None)

    super(ConceptForm, self).__init__(*args, **kwargs)

    if self.action is not None:
      if self.action == 'detail':
        for field in self.fields:
          self.fields[field].widget.attrs['readonly'] = True

views.py

modelformset = modelformset_factory(
  model = model,
  fields = show_fields,
  form = ConceptForm(kwargs={'action': 'detail'), <-- I would like something like this
)

The error is:

'ConceptForm' object is not callable

Without call init not errors showed but the form fields not are disabled

modelformset = modelformset_factory(
  model = model,
  fields = show_fields,
  form = ConceptForm
)

Thanks in advance

like image 951
Alberto Sanmartin Martinez Avatar asked Sep 05 '25 23:09

Alberto Sanmartin Martinez


1 Answers

As is specified in the Passing custom parameters to formset forms section of the documentation, you can make use of the form_kwargs=… parameter of the FormSet:

ConceptFormSet = modelformset_factory(
    model = Concept,
    form = ConceptForm,
    fields = show_fields
)
formset = ConceptFormSet(form_kwargs={'action': 'detail'})
like image 185
Willem Van Onsem Avatar answered Sep 08 '25 17:09

Willem Van Onsem