0

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.

1
  • How did you define LineItemsInlineFormSet? If you've created your own subclass, did you remember to use **kwargs in its __init__? Commented Dec 7, 2010 at 18:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This approach gives you a bound formset, which will display validation errors if all required data is not provided.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.