Django以editprofile形式传递request.POST和request.FILES

时间:2010-11-02 21:14:50

标签: django django-forms request

我有一个视图,使用户能够在ÌmageField中编辑他们的个人资料(通常的姓名,用户名等)和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))

,表格是:

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

问题是我需要将`request.FILES'传递给表单! 我试过了

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

和其他没有成功的变种。

3 个答案:

答案 0 :(得分:3)

当你覆盖表单的构造函数时,最好传递名为而不是按顺序的参数。所以,我会这样做:

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

这样一来,读取代码的人很清楚你有一个非标准形式需要一个用户参数,它会明确你传递的参数。

或者,如果你坚持在没有命名参数的情况下调用构造函数,那么正确的方法是:

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

因为user是构造函数的第一个参数。

答案 1 :(得分:0)

尝试

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

答案 2 :(得分:0)

覆盖表单的__init__最安全的方法是监听额外的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

这使得表单的原始签名基本上不受影响,您可以正常实例化它,并在最后添加额外的参数:

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