我做了一个视图,以更新用户配置文件。上传图片时图片保存正确,但再次更新配置文件时,图片不再保存,我该如何解决这个问题?我很高兴有任何帮助!
我的类 UserProfile 如下所示:
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',)
如果还有其他必要的广告,我很乐意补充。
我很高兴有任何帮助!