在编辑个人资料表单中显示当前用户实例

时间:2018-03-08 20:14:35

标签: python django

所以我有这个显示我的UserProfileForm的视图。据我所知,正在发生的事情的逻辑是有道理的。它应该(1)自动从当前登录的用户中提取配置文件信息,并(2)在提交时保存。唯一的问题是它既没有做这两件事。

我已经了解了如何执行此操作以及其他一些教程,但它仍然没有做到这一点。

观点:

def editProfileView(request):
    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=request.user)

        if form.is_valid():
            form.save()
            return redirect('users:explore')
    else:
        form = UserProfileForm(instance=request.user)
        args = {'form':form}
        return render(request, 'users/userprofile_edit_form.html', args)

不确定看到表单本身有多相关,但这就是它的样子:

class UserProfileForm(forms.ModelForm):
    first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))
    profile_pic = forms.ImageField(widget=forms.FileInput(attrs={'class':'form-control mb-3'}), required=False)
    location = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))
    title = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))
    user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES)
    website = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))
    about = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control mb-3'}))
    twitter = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))
    dribbble = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))
    github = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control mb-3'}))

    class Meta:
        model = UserProfile
        fields = (
            'first_name',
            'profile_pic',
            'location',
            'title',
            'user_type',
            'website',
            'about',
            'twitter',
            'dribbble',
            'github'
        )

1 个答案:

答案 0 :(得分:2)

我猜测UserProfile模型是一个与用户模型不同的模型,并通过一些外键连接。我在帖子中看不到模型,但如果foreignkey有related_name ='user_profile'你应该改变

instance = request.user

instance = request.user.user_profile