0

I have a Django model with the implemented Django admin interface and I want to display the form for the model. If the form displays only the attributes of the model, it's a simple task. My problem is that I would like to change the fields of the form depending on the user authenticated. Is there any way how to pass extra data (user) as an argument to the ModelForm init function from the admin? I found some tutorials, but their implementation worked only for basic views, not for the Admin implementation.

I have also tried to pass an extra argument to the admin get_form() function, but it is not possible to. I get the error that an unexpected argument was provided.

My Form:

Class ProfileForm(forms.ModelForm):
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
    model = Profile

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        interests = ProfileInterest.objects.filter(
            user=user # HERE I WOULD LIKE TO ACCESS THE USER (request.user)
        )
        for i in range(len(interests) + 1):
            field_name = 'interest_%s' % (i,)
            self.fields[field_name] = forms.CharField(required=False)
            try:
                self.initial[field_name] = interests[i].interest
            except IndexError:
                self.initial[field_name] = “”
        # create an extra blank field
        field_name = 'interest_%s' % (i + 1,)
        self.fields[field_name] = forms.CharField(required=False)

I'm trying to filter the ProfileInterest queryset by the user and then displaying them as form fields. I need to pas the user instance somehow to the form from the Admin definition.

pe.kne
  • 655
  • 3
  • 16

0 Answers0