在Django中使用自定义用户模型时的RelatedObjectDoesNotExist

时间:2016-07-02 17:28:41

标签: django

我有一个帐户应用,我通过扩展自定义用户模型创建了个人资料模型。我创建了一个视图,允许用户编辑他的个人资料信息,我也有相应的UserEditForm和ProfileEditForm。截至目前,没有用户有个人资料,所以当我打开编辑表单时,我收到一个错误:“/ object / edit /”中的“RelatedObjectDoesNotExist”。 “用户没有个人资料” 我尝试使用admin创建配置文件,然后错误就消失了。如何在views.py文件中更正此内容。

views.py

@login_required
def edit(request):
    if request.method =='POST':
        user_form = UserEditForm(instance=request.user,data=request.POST)

        profile_form =     ProfileEditForm(instance=request.user.profile,data=request.POST,files=request.FILES)

        if user_form.is_valid() and profile_form.is_valid():
            user_form.save()
            profile_form.save()
            messages.success(request,'Profile updated successfully')

        else:
            messages.error(request,'Error updating your profile')

    else:
        user_form = UserEditForm(instance=request.user)

        profile_form = ProfileEditForm(instance=request.user.profile)


    context = {
        'user_form':user_form,
        'profile_form': profile_form
    }
    return render(request,'account/edit.html',context)

models.py

CATEGORY_CHOICES = (
    ('SA','School Admin'),
    ('T','Teacher'),
    ('S','Student'),
    ('P','Parent'),
)


class Profile(models.Model):
    eduser = models.OneToOneField(settings.AUTH_USER_MODEL)
    photo = models.ImageField(upload_to='users/%Y/%m/%d',blank=True)
    about_me = models.TextField(max_length=200,blank=True)
    category = models.CharField(max_length=1,choices=CATEGORY_CHOICES,blank=True)
    date_of_birth = models.DateField(blank=True,null=True)

    def __str__(self):
        return 'Profile for user {}'.format(self.eduser.username)

forms.py

class UserEditForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ('first_name','last_name','email')

class ProfileEditForm(forms.ModelForm):

    class Meta:
        model = Profile
        fields = ('category','date_of_birth','about_me','photo')

1 个答案:

答案 0 :(得分:3)

您需要捕获错误。你可以在函数的顶部做到这一点:

try:
    profile = request.user.profile
except ObjectDoesNotExist:
    profile = Profile(user=request.user)

并将profile传递给两个if分支中的ProfileEditForm。