Search code examples
pythondjangodjango-formsformset

'User' object has no attribute 'get' with formset (passing user to get a queryset)


I am trying to display a formset for a particular User.

If the user is on the 'medical tab', then it should display a tiny form (a checkbox and a text box) for each dependent of the user.

In my views.py I have this:

def get_dep_form(benefit_tab, user):
    if benefit_tab == 'medical':
        DepMedFormSet = formset_factory(DependentMedicalBenefitForm)
        link_formset =  DepMedFormSet(user)
    else:
        return None
    return link_formset

In my forms.py I have this:

class DependentMedicalBenefitForm(forms.ModelForm):
    has_medical = forms.BooleanField()
    med_group_id = forms.CharField(max_length=10)
    class Meta:
        model = Dependent
        fields = [
            'has_medical', 'med_group_id'
        ]

    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user')
        queryset = Dependent.objects.filter(employee=self.user)
        super(DependentMedicalBenefitForm, self).__init__(*args, **kwargs)
        self.fields['has_medical'].queryset = queryset
        self.fields['med_group_id'].queryset = queryset

In my views.py I'm getting the form like this:

def index(request, benefit_tab=None):
     #stuff
     if benefit_tab:
          link_formset = get_dep_form(benefit_tab, request.user)
return render(request, 'benefits/index.html', {
     #stuff
     'link_formset': link_formset,
})

I am running into the error: 'User' object has no attribute 'get'

If I don't pass a user, and comment out the init function, then it displays a single checkbox and textbox as expected - but I can't figure out why passing the user this way is not working.

Bonus points: if you know how to prepopulate the formset with the respective data - that is next up once I get past the 'User' error.


Solution

  • You are passing the user as a positional argument to the instantiation of the formset, but the formset is expecting the POST data there. What you want is to pass that value to the forms, as a keyword arg.

    Luckily, since Django 1.9 formsets support this via the form_kwargs argument. So you should do:

    link_formset =  DepMedFormSet(form_kwargs={'user': user})
    

    You don't show the code where you process that formset, but remember to also pass that form_kwarg there too.