I have a view that enables users to edit their profiles (usual name, username etc) and a image contained in an ÌmageField within the UserProfile:
@login_required
def editprofile(request):
user = request.user
if request.method == 'POST':
edit_form = EditProfileForm(data = request.POST, user = user)
if edit_form.is_valid():
user = edit_form.save()
request.user.message_set.create(message='Votre profil a été modifié.')
return HttpResponseRedirect('/')
else:
dict = {'first_name':user.first_name, 'last_name':user.last_name, 'email':user.email, 'username':user.username}
edit_form = EditProfileForm(user = user, data = dict)
tpl_dict = {'form' : edit_form}
return render_to_response('editprofile.html', tpl_dict, RequestContext(request))
and the form is:
class EditProfileForm(forms.Form):
first_name = forms.CharField(max_length = 100, required=False)
last_name = forms.CharField(max_length = 100, required=False)
email = forms.EmailField()
username = forms.CharField(max_length = 100)
avatar = forms.ImageField(required = False)
def __init__(self, user, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
self.user = user
def save(self):
user = self.user
user.email = self.cleaned_data['email']
user.username = self.cleaned_data['username']
user.first_name = self.cleaned_data['first_name']
user.last_name = self.cleaned_data['last_name']
user.save()
profile = user.get_profile()
profile.avatar = self.cleaned_data['avatar']
profile.save()
return user
the problem is that i need to pass a `request.FILES’ to the form!
I’ve tried
edit_form = EditProfileForm(data = request.POST, request.FILES, user = user)
and other variants without succes.
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:
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:
since
useris the first argument to your constructor.