Passing a Parameter to a Django Form

This is somewhat related to my previous post. I didn’t want to include my user profile value in the form and instead add it during validation. This caused the model validation to be skipped in part. I had to do some gymnastics to get it to run.

In this latest attempt, I have instead included that profile as a hidden field and compare it to the current user profile. Much cleaner! Now all I have to to is get that current value into the form.

It didn’t take long on Google to find several examples. Here is my rendition:

In the view, I overrode the get_form method to add the profile as a paramter

def get_form(self, form_class=None):

    if form_class is None:
        form_class = self.get_form_class()
    return form_class(**self.get_form_kwargs(),current_user_profile=get_profile(self.request.user))

Next, in the form I need to pop that value from the kwargs dictionary as assign to a object variable

class LinkForm(ModelForm):

        def __init__(self, *args, **kwargs):

            self.current_user_profile = kwargs.pop('current_user_profile')

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

            self.fields['profile'].widget=HiddenInput()

I also set the profile field to hidden here.

Now I can write a clean method for the profile field like so:

def clean_profile(self):

        profile = self.cleaned_data.get('profile',None)

        if profile != self.current_user_profile:
            self.add_error(None,ValidationError('Web page altered. Try again.', code='wrong_profile'))

        return profile

This is much easier and clearer than my previous method. Not bad for working late on a Wednesday night.