Same URL in multiple views in Django

丶灬走出姿态 提交于 2019-12-03 12:58:41

To handle that kind of thing you can use a single view that follows different code paths depending on the request state. That can mean something simple like setting a context variable to activate a sign in button, or something as complex and flexible as calling different functions - eg, you could write your home and main functions, then have a single dispatch view that calls them depending on the authentication state and returns the HTTPResponse object.

If authentication is all you need to check for, you don't even need to set a context variable - just use a RequestContext instance, such as the one you automatically get if you use the render shortcut. If you do that, request will be in the context so your template can check things like {% if request.user.is_authenticated %}.

Some examples:

def dispatch(request):
    if request.user.is_authenticated:
        return main(request)
    else:
        return home(request)

Or for the simpler case:

def home(request):
    if request.user.is_authenticated:
        template = "main.html"
    else:
        template = "home.html"
    return render(request, template)
David Viktora

While looking into a similar problem, I found an application - django-multiurl. It has its limitations, but it is very convenient and useful.

Basically it allows you to raise a ContinueResolving exception in a view, which will result in next view being processed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!