不要在Django中更新头像图片

时间:2019-08-23 01:20:26

标签: django

我想更新个人资料图片,好像它没有保存在项目中一样。怎么了?

views.py

@login_required
def edit_profile(request):
    if request.method == 'POST':
        form = EditProfileForm(request.POST,request.FILES,instance=request.user)
        if form.is_valid():
            form.save()
            return redirect('/perfil')
    else:
        form = EditProfileForm(instance=request.user.usuario)
    context = {'form': form}
    return render(request, 'polls/edit_profile.html', context)

forms.py

class EditProfileForm(forms.ModelForm):
    avatar = forms.ImageField(label='Foto de perfil')
            class Meta:
        model = User
        fields = ['username','first_name', 'last_name','matricula','email','avatar','tipoUsuario']

models.py

class Usuario(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    avatar = models.ImageField('Foto de perfil',upload_to='static/img/uploads/profile_photo',default="static/img/user.jpg")

1 个答案:

答案 0 :(得分:1)

您还必须更新您的Usuario模型。您可以尝试如下操作:

if request.method == 'POST':
        form = EditProfileForm(request.POST,request.FILES,instance=request.user)
        if form.is_valid():
            avatar = form.cleaned_data['avatar']
            user = form.save()           
            user.usuario.avatar = avatar
            user.usuario.save()
            return redirect('/perfil')