[Django]-Django pass request.POST and request.FILES in a editprofile form


When you are overriding the constructor of a form it is a good idea to pass the arguments named instead of just in order. So, I would do:

edit_form = EditProfileForm(user=user, data=request.POST, files=request.FILES)

That way it is clear to someone reading the code that you have a non-standard form that expects a user argument and it makes explicit which arguments you are passing.

Alternatively, if you’d insist on calling the constructor without naming the arguments, the correct way to do so is:

edit_form = EditProfileForm(user, request.POST, request.FILES)

since user is the first argument to your constructor.




edit_form = EditProfileForm(request.POST, request.FILES, user = user)


The safest way to override a form’s __init__ is to listen for extra kwargs:

class EditProfileForm(forms.Form):
    # [fields]

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', default_user) # fetch `user` and remove from kwargs
        super(EditProfileForm, self).__init__(*args, **kwargs)
        self.user = user

This leaves the form’s original signature essentially untouched, and you can instantiate it as normal, with your extra argument tacked on the end:

EditProfileForm(request.POST, user=user)
EditProfileForm(request.POST, request.FILES, user=user)


Leave a comment