gpt4 book ai didi

python - 更新用户个人资料时 upload_to 不起作用?

转载 作者:行者123 更新时间:2023-12-01 04:03:28 25 4
gpt4 key购买 nike

当我的用户创建个人资料时,他们的图像保存得很好,但当他们更新它时,图像不会保存。我也不知道如何提取图片以便他们在更新之前可以看到它。

这是表格:

class UpdateProfileForm(forms.ModelForm):
city = models.ForeignKey(City)

class Meta:
model = UserProfile
fields = ('city', 'profilepic')

def save(self, commit=True):
profile = super(UpdateProfileForm, self).save(commit=False)

if commit:
profile.save()
return profile

这是 View :

def updateprofile(request):



if request.method == 'POST':
update_user_form = UpdateUserForm(request.POST, instance=request.user)
update_profile_form = UpdateProfileForm(request.POST, request.FILES, instance=request.user.profile)

if update_user_form.is_valid() and update_profile_form.is_valid():
update_user_form.save()

'''************************************************'''
profile = update_profile_form.save(commit=False)

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

profile.save()

'''************************************************'''


return HttpResponseRedirect(reverse('index'))
else:
update_user_form = UpdateUserForm(instance=request.user)
update_profile_form = UpdateProfileForm(instance=request.user.profile)


return render(request, 'updateprofile.html', {'update_user_form' : update_user_form, 'update_profile_form' : update_profile_form})

这是模型:

# this is model for user
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')

hobbies = models.ManyToManyField(Hobby)
languages = models.ManyToManyField(Language)

profilepic = models.ImageField(upload_to='static/images/Profile Pictures', blank=True)
city = models.ForeignKey(City)
slug = models.SlugField(unique=True)

average_rating = models.IntegerField(default=0)
ratings_count = models.IntegerField(default=0)

def save(self, *args, **kwargs):
# Uncomment if you don't want the slug to change every time the name changes
self.slug = slugify(self.user.username)
super(UserProfile, self).save(*args, **kwargs)

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

谢谢。

最佳答案

将 request.FILES 添加到表单中:

update_profile_form = UpdateProfileForm(request.POST, request.FILES,
instance=request.user)

默认情况下,django 不包含 request.POST 中的文件

此外,我认为 UserProfile 模型的实例应该是 request.user.profile 而不是 request.user 或者我在这里遗漏了一些东西?

按照 django-docs 的说明进行操作

关于python - 更新用户个人资料时 upload_to 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36101336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com