, 'collection.views.home', name='...">

Same url in multiple views in Django

I am 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 the main page, otherwise go to the main page. On the home page, otherwise there will be a sign in the button. But they must be on the same URL pattern.

How can I handle this?

+6
source share
2 answers

To deal with such things, you can use one view that follows different code codes depending on the status of the request. This may mean something simple, like setting a context variable to activate the login button, or something as complex and flexible as calling various functions - for example, you could write your home and main functions and then have one view sending, which calls them depending on the authentication state and returns an HTTPResponse object.

If authentication is required for verification, you don’t even need to set a context variable - just use an instance of RequestContext , for example one that you will automatically receive if you use the render shortcut. If you do this, request will be in context so that 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 a simpler case:

 def home(request): if request.user.is_authenticated: template = "main.html" else: template = "home.html" return render(request, template) 
+7
source

Studying a similar problem, I found an application - django-multiurl . This has its limitations, but it is very convenient and useful.

This basically allows you to throw a ContinueResolving exception in the view, which will result in the following processing.

0
source

Source: https://habr.com/ru/post/971017/


All Articles