Same URL in multiple views in Django

2020-06-17 04:52发布

问题:

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.