darren
darren

Reputation: 19399

How to pass a request into an inline form set using django-extra-views

I have a form with an inline form set. What I would like to do is when the user lands on the form, to have his user information (name for example) prepopulated into one of the inlines of the form. To be able to pass the request through to the inlines.

How can I do this?

I'm using django-extra-views 0.6 on Django 1.4

In views.py I'm using the get_extra_form_kwargs def to setup my kwargs like so:

class EventMemberInline(InlineFormSet):
    model = EventMember
    extra = 1
    form_class = EventMemberForm

    def get_formset_kwargs(self):
        formset_kwargs = super(EventMemberInline, self).get_formset_kwargs()
        formset_kwargs.update({'first_name':self.request.user.first_name, 'last_name':self.request.user.last_name})
        return formset_kwargs

I'm doing that in the attempt that I will be able to bind the fields of my inlines(initial values) to what I pass through the kwargs(in this case just user first_name and last_name)

In forms.py

class EventMemberForm(ModelForm):

    class Meta:
        model = EventMember

    def __init__(self, *args, **kwargs):
        self.fields['first_name'].initial = kwargs['first_name']
        self.fields['last_name'].initial = kwargs['last_name']
        super(EventMemberForm, self).__init__(*args, **kwargs)

But I get this error:

Exception Value:    

__init__() got an unexpected keyword argument 'last_name'

Is what I'm trying to do even possible? Can I set the initial value of an inline?

Upvotes: 2

Views: 1950

Answers (1)

Andrew Ingram
Andrew Ingram

Reputation: 5220

There was an issue with django-extra-views==0.6.0 that meant get_extra_form_kwargs wasn't being called for inlines, it should be fixed in 0.6.1.

This should work:

class EventMemberInline(InlineFormSet):
    model = EventMember
    extra = 1
    form_class = EventMemberForm

    def get_extra_form_kwargs(self):
        kwargs = super(EventMemberInline, self).get_extra_form_kwargs()
        kwargs.update({
            'first_name': self.request.user.first_name,
            'last_name': self.request.user.last_name
        })
        return kwargs

...

class EventMemberForm(ModelForm):

    class Meta:
        model = EventMember

    def __init__(self, *args, **kwargs):
        initial_first_name = kwargs.pop('first_name')
        initial_last_name = kwargs.pop('last_name')

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

        self.fields['first_name'].initial = initial_first_name
        self.fields['last_name'].initial = initial_last_name

Upvotes: 3

Related Questions