Image uploaded but not saved in media and database Django

前端 未结 1 1667
别那么骄傲
别那么骄傲 2021-01-23 17:41

Am creating a settings page where the user should be able to chang there image and biodata. But only the biodata gets updated when I print the request.FILES.GET("profile_pi

相关标签:
1条回答
  • 2021-01-23 18:00

    There is a trailing comma in the line:

    #                    trailing comma ↓
    user.profile_picture=profile_picture,

    you need to remove this.

    That being said, I would advice to use a ModelForm, this can remove a lot of boilerplate code:

    class ProfileForm(forms.Form):
    
        class Meta:
            model = User
            fields = ['profile_pic', 'bio']
            labels = {
                'profile_pic': 'Profile picture'
            }
            widgets = {
                'bio': forms.Textarea
            }

    Then in the view, we can use:

    from django.contrib.auth.decorators import login_required
    
    @login_required
    def settings(request):
        if request.method == 'POST':
             profile_form = ProfileForm(request.POST, request.FILES, instance=request.user)
             if profile_form.is_valid():
                 profile_form.save()
                 return redirect('home')
        else:
            profile_form = ProfileForm(instance=request.user)
        context ={
            'profile_form': profile_form
        }
        return render(request, 'user/settings.html', context)
    0 讨论(0)
提交回复
热议问题