python 没有PK或Slug的Django Generic DetailView

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 没有PK或Slug的Django Generic DetailView相关的知识,希望对你有一定的参考价值。

# For the most part this is fine as you’ll usually provide an identifier in the URL. 
# But what if you need to pull the identifier from someplace else such as the session?

# To accomplish this, simply override the get_object method:


class UserView(DetailView):

    template_name = 'template.html'
    #model = User
    #context_object_name = 'foo'

    def get_object(self):
        return get_object_or_404(User, pk=request.session['user_id'])

# Also note that the model is no longer necessary as you’re explicitly calling it in get_object. 
# The object is now available in the template using the model name, in this case user:

# {{ user.id }}

# You can override this name by using context_object_name.

# https://chriskief.com/2012/12/29/django-generic-detailview-without-a-pk-or-slug/

以上是关于python 没有PK或Slug的Django Generic DetailView的主要内容,如果未能解决你的问题,请参考以下文章

将 Pk 或 Slug 传递给 Django 中的通用 DetailView?

如何为 DetailView 指定 pk 或 slug 以外的其他内容

难以将 slug 添加到 Django 中的通用详细信息视图

通用详细视图 UserProfileDetailView 必须在 URLconf 中使用对象 pk 或 slug 调用

Django 在 URL 中访问 PK/Object

Django:两个模型中的一个 url 搜索(cbv)