pokiman
pokiman

Reputation: 986

Setting a default value for a field in a formset in Django

In a formset in Django, how do we set a default value for a field which needs a value from the http session? Since a session is required to get the value, we cannot set a default value in the model class itself. And I am not able to understand how to explicitly set the value in each form in the formset before saving in the view function.

Setting the initial attribute in the construction of the FormSet would work but for whatever reason, I get a compilation error. The code is like this:

formset = LineItemsInlineFormSet(initial=[{'updated_by':'user'}])

The compilation error is: init() got an unexpected keyword argument 'initial'

I am using Django 1.1.1

Any insight will be appreciated. Thanks in Advance.

Upvotes: 0

Views: 3826

Answers (1)

Paulo Scardine
Paulo Scardine

Reputation: 77251

The idiom to instance a formset with initial data is:

data = {
     'form-TOTAL_FORMS': u'2',
     'form-INITIAL_FORMS': u'0',
     'form-MAX_NUM_FORMS': u'',
     'form-0-updated_by': u'user',
     'form-1-updated_by': u'user',
}

formset = LineItemsInlineFormSet(data)

Update:

As Jonny Buchanan noted, this approach gives you a bound formset, which will display validation errors if all required data is not provided. If it is not what you want, create your formset passing a custom Form with desired settings to django.forms.formsets.formset_factory().

It is common to set updated_by as the current logged-in user automagically upon update. If this is what you want:

  1. omit the updated_by field in the form;
  2. save() with commit=False if it is a ModelFormset;
  3. set updated_by to current user; and
  4. save object instances, now with the default commit=True.

In the admin site there is a convenient way to do this with inlines: overrride ModelAdmin.save_formset.

Upvotes: 1

Related Questions