PabloVallejo
3/19/2014 - 3:09 PM

form-get-current-user.py

# views.py
class UserProfileUpdate(LoginRequiredMixin, UpdateView):
    
    # ...

    # Pass current user to form through `initial`
    def get_form_kwargs(self, **kwargs):
        kwargs = super(UserProfileUpdate, self).get_form_kwargs(**kwargs)
        kwargs['initial']['user']=self.request.user
        return kwargs

    # ...


# forms.py
class UserUpdateForm(forms.ModelForm):
	
	# ...

	def __init__(self, *args, **kwargs):
		
		# Getting the user calling the parent save method, 
		# might trigger an unhandled error. 
		# 	
		# 	user = super(UserUpdateForm, self).save(commit=False)
		# 	
		# So, we could get the current user from the `initial` attrbute
		# set in the `views.py`. 
		self.user = self.initial['user']