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

时间:2016-03-19 11:50:05

标签: python django django-forms django-views

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

这是表格:

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

这是观点:

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

谢谢。

1 个答案:

答案 0 :(得分:2)

将request.FILES添加到表单:

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

默认情况下,django不包含request.POST

中的文件

另外,我认为UserProfile模型的实例应该是request.user.profile而不是request.user,或者我在这里遗漏了什么?

按照django-docs

的说明操作