Same URL in multiple views in Django

被刻印的时光 ゝ 提交于 2020-01-01 04:53:28

问题


I'm developing a web application, and I need something like this:

url(r'^$', 'collection.views.home', name='home'),
url(r'^$', 'collection.views.main', name='main'),

If the user is authenticated, go to main, otherwise go to home. On the home page, differently there will be a sign in a button. But these should be on the same URL pattern.

How can I handle it?


回答1:


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)



回答2:


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.



来源:https://stackoverflow.com/questions/24289095/same-url-in-multiple-views-in-django

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