Home > Back-end >  Pass request.user parameter to modelformset_factory form
Pass request.user parameter to modelformset_factory form

Time:11-14

So I've a formset tied to a model and one of the fields in that is ForeignKey.

models.py

class Squad(models.Model):
    rid = models.AutoField(primary_key=True)        
    team = models.ForeignKey(Team, on_delete=models.CASCADE)    

    def __str__(self):
        return self.team.tname

forms.py

class SquadForm(ModelForm):     
    class Meta:
        model = Squad    

    def __init__(self, logged_user, user, *args, **kwargs):
        super(SquadForm, self).__init__(*args, **kwargs)
        self.fields['team'] = forms.ModelChoiceField(queryset=Team.rows.get_my_teams(user=logged_user), empty_label="None")

As you can see, the __init__ function is expecting an extra parameter logged_user which I'm hoping to pass via the views.py file. But if I do the following:

views.py

def choose_teams(request):      
    teamformset = modelformset_factory(Squad, extra=2, form=SquadForm(request.user))

    form = teamformset(queryset=Squad.objects.none())
    return render(request, 'foo.html', {'form':form})

I'm trying to pass the logged in user as a parameter on line 2 but this is resulting in the following message:

Field 'id' expected a number but got 'SquadForm'

Not sure what I'm missing here. But if I remove the parameter from line 2:

teamformset = modelformset_factory(Squad, extra=series.team_number, form=SquadForm)

it starts working (of course, I no longer expect the user in the forms.py file and remove it too) but shows all the data and not filtered one.

CodePudding user response:

You can pass additional keyword arguments to your formset form by passing form_kwargs={} to your formset

class SquadForm(ModelForm):     
    class Meta:
        model = Squad    

    def __init__(self, *args, logged_user, **kwargs):
        super(SquadForm, self).__init__(*args, **kwargs)
        self.fields['team'] = forms.ModelChoiceField(queryset=Team.rows.get_my_teams(user=logged_user), empty_label="None")


teamformset = modelformset_factory(Squad, extra=2, form=SquadForm)
form = teamformset(queryset=Squad.objects.none(), form_kwargs={'logged_user': request.user})
  • Related