Django:如何通过ModelForm更新个人资料图片?

时间:2015-03-25 02:31:37

标签: python django django-forms

我正在尝试编写一个小型Django系统。登录系统后,用户可以编辑并保存他/她自己的个人资料信息。涉及的字段包括:用户名,电子邮件,名字,姓氏,网站和图片。

问题:图片无法更新(选择图片并点击“更新”按钮后,显示“未选择文件”。页面上显示的个人资料图片仍为旧图片)。但其他领域都没问题。

以下是我的代码:

models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User)

    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to="profile_images", blank=True)

    def __str__(self):
        return self.user.username

forms.py

class UserForm2(forms.ModelForm):

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name', 'last_name')

class UserProfileForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ('website', 'picture')

views.py

@login_required
def update_user(request):

    try:
        user_profile = UserProfile.objects.get(user=request.user)
    except UserProfile.DoesNotExist:
        return HttpResponse("invalid user_profile!")

    if request.method == "POST":
        update_user_form = UserForm2(data=request.POST, instance=request.user)
        update_profile_form = UserProfileForm(data=request.POST, instance=user_profile)

        if update_user_form.is_valid() and update_profile_form.is_valid():
            user = update_user_form.save()
            profile = update_profile_form.save(commit=False)
            profile.user = user

            if 'picture' in request.FILES:
                profile.picture = request.FILES['picture']

            profile.save()

        else:
            print(update_user_form.errors, update_profile_form.errors)
    else:
        update_user_form = UserForm2(instance=request.user)
        update_profile_form = UserProfileForm(instance=user_profile)

    return render(request,
            'userprofile/update_user.html',
            {'update_user_form': update_user_form, 'update_profile_form': update_profile_form}
            )

update_user.html

<form id="update_user_form" method="POST" action="/userprofile/update_user/">
    {% csrf_token %}
    {{ update_user_form.as_p }}
    {{ update_profile_form.as_p }}
    <img src="{{ update_profile_form.instance.picture.url }}" />
    <br />
    <input type="SUBMIT" name="submit" value="Update"/>
</form>

如何使其正常工作?

1 个答案:

答案 0 :(得分:3)

要上传文件,您应将enctype属性添加到<form>标记:

<form id="update_user_form" method="POST" action="/userprofile/update_user/"
                            enctype="multipart/form-data">