user1112008
user1112008

Reputation: 442

How to show different view for logged user in Django?

Let's say I have following views ScheduleList where user (logged or not) can see task list by selected day and PersonalizedScheduleList where user can see all tasks belong to him (he have to be logged in). I could use one ListView and in get_queryset method put big if for authenticated user and not - data process is different.

How to show different view on the same url pattern for logged and not logged users so logged user can see his schedule list on the main page and not logged can see tasks by selecting the day?

urlpattern('',
 url(r'^$', views.ScheduleList.as_view()), # not logged user
 url(r'^$', views.PersonalizedScheduleList.as_view()), # logged user
)

Upvotes: 3

Views: 1153

Answers (2)

orokusaki
orokusaki

Reputation: 57188

You need to think about the control-flow of request handling and URL routing. A request is received, Django finds the first URL pattern that matches the request's URL and calls the function assigned to that URL (or in your case, a class with a __call__ method defined (CBV implementation detail). This means, you couldn't, at a URL-routing level, assign one view over another, based simply on header values (authentication is typically based on some header; cookie, etc.), unless the URL was different.

Solutions

  1. Write a sort of interceptor view which delegates the the other view, based on the login status of the incoming request (this would be simply a view whose get/post methods return the result of calling one of the two views mentioned in your question)
  2. Design the workflow of your app to send the user to the correct view, having each view at a different URL path (this is the cleaner way of handling things) - your in-page JavaScript could handle this client-side, while the backend protects from accidental (or malicious) access attempts to the wrong view

Upvotes: 1

Laur Ivan
Laur Ivan

Reputation: 4177

IMHO the best practice is to provide a single view and do something like:

{% if request.user.is_authenticated %}
.... Authenticated content
{% else %}
.... non-authenticated content
{% endif %}

If you want to do 2 separate views, you'd need to redirect from/to the personalised view (probably in both views).

Upvotes: 0

Related Questions