(Django) 通过更新 UserProfile,图像没有正确保存

(Django) By updating the UserProfile, the image is not saving correctly

我做了一个更新用户配置文件的视图。上传图片时图片保存正确,但再次更新配置文件时,图片不再保存,请问如何解决?我很高兴能得到任何帮助!

我的 class 用户配置文件如下所示:

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.TextField(max_length=500, blank = True, default=('keine Angabe'), null=True)
    image = models.FileField(null=True, blank=True)
    facebook = models.CharField(max_length=200, null=True,default=('keine Angabe'))

    def get_absolute_url(self):
        return reverse('gaestebuch:result', args=[str(self.id)])

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

    @property
    def get_content_type(self):
        instance = self
        content_type =   ContentType.objects.get_for_models(instance.__class__)
        return content_type

我使用两个视图:

def update_profile(request):
    userProfile = UserProfile.objects.get(user=request.user)
    form = UserProfileForm(initial={'bio': userProfile.bio, 'image' : userProfile.image, 'facebook': userProfile.facebook})
    return render_to_response('gaestebuch/update_profile.html', {'form':form}, RequestContext(request))


@login_required
def send_update_profile(request):
    if request.method == 'POST':
        #form = UserProfileForm(request.POST)
        form = UserProfileForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            userProfile = UserProfile.objects.get(user=request.user)
            bio = form.cleaned_data['bio']
            userProfile.bio = bio
            image = form.cleaned_data['image']
            userProfile.image = image
            facebook = form.cleaned_data['facebook']
            userProfile.facebook = facebook
        userProfile.save()
        return redirect('the url' + str(userProfile.id))
    else:
        form = UserProfileForm()
    return redirect('/user/send_update_profile')

这是我的表格:

class UserProfileForm(forms.ModelForm):

    class Meta:
        model = UserProfile
        fields = ('bio','image','facebook',)

如果还有什么需要广告的,我很乐意补充。

很高兴能得到任何帮助!

由于您使用的是 ModelForm 子类而不是 Form 子类,因此您应该利用它的功能,尤其是 save method.

Every ModelForm also has a save() method. This method creates and saves a database object from the data bound to the form. A subclass of ModelForm can accept an existing model instance as the keyword argument instance; if this is supplied, save() will update that instance. If it’s not supplied, save() will create a new instance of the specified model

因此您的代码可以简化为

form = UserProfileForm(request.POST or None, request.FILES or None)
if form.is_valid():
    form.save()
    return redirect('the url' + str(userProfile.id))

 else:
    return render_to_response(
        'gaestebuch/update_profile.html', {'form':form}, RequestContext(request))

附带说明一下,在编写新的 Django 代码时使用 render 而不是 render_to_response 因为 render_to_response 计划在未来被弃用并最终被删除。