Python/Django UserProfile.objects.get()方法

0 投票
2 回答
2316 浏览
提问于 2025-04-18 12:59

我看到下面的代码,我想问的是,为什么在我通过 User.objects.get(username=request.user) 获取到用户信息后, UserProfile.objects.get 却返回了 None?在这个 try 语句中还有什么其他的事情发生导致失败吗?我刚开始学 Django,请多多包涵我的无知。

def profile(request):
    context = RequestContext(request)
    cat_list = get_category_list()
    context_dict = {'cat_list': cat_list}
    u = User.objects.get(username=request.user)


    try:
        up = UserProfile.objects.get(user=u)
    except:
        up = None

    print u   #this one prints out the user
    print up  #this prints 'None'
    context_dict['user'] = u
    context_dict['userprofile'] = up
    return render_to_response('blog/profile.html', context_dict, context)

models.py

class UserProfile(models.Model):

    user = models.OneToOneField(User)

    website = models.URLField(blank=True)
    picture = models.ImageField(upload_to='profile_images', blank = True)

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

2 个回答

0

你为什么认为一定会有一个和这个 User 相关的 UserProfile 呢?其实并没有什么保证说一定会有。

你应该按照文档里的说明来正确设置 UserProfile 类,这样你的视图代码可以简化成这样:

def profile(request):
    return render(request, 'blog/profile.html', {'cat_list': get_category_list(),
                                                 'user': request.user,
                                                 'profile': user.get_profile(),
                                                 })

如果你想在个人资料不存在时做一些特别的处理,可以这样做:

def profile(request):
    try:
        profile = user.get_profile()
    except ObjectDoesNotExist:
        profile = None
    return render(request, 'blog/profile.html', {'cat_list': get_category_list(),
                                                 'user': request.user,
                                                 'profile': profile,
                                                 })
0

我来回答我自己的问题,因为可能还有其他人会遇到同样的情况...

当我去掉了那个尝试/异常处理的代码块后,我发现我需要添加

`AUTH_PROFILE_MODULE = AppName.UserProfileClassName` 

在我的情况下

AUTH_PROFILE_MODULE = blog.UserProfile`

添加之后我又试了一次,但出现了 UserProfile matching query does not exist 的错误,这个错误通常是在你用管理员账户登录时会出现的。所以,当我用普通账户登录后,一切都正常了!

撰写回答