Max S
Max S

Reputation: 41

Django view chaining/redirecting best practices

I'm building an app that starts with a landing page where users can login or signup. I've got two different types of users who will be taken to two different dashboard pages upon being logged in successfully (I know which kind of user is logging in based on their credentials).

My question is about the best way to handle this view-wise. My Login view has the logic to tell which kind of user I'm getting, and then properly renders the template for that kind of user's dashboard. However, I've also got a separate view for each kind of dashboard that renders the same templates the same way as in the Login view -- this is for when users click the "home" button or what have you. It seems silly to repeat logic like that (plus now there are two URLs for each dashboard -- 'login/' and 'dashboard_x/'), so I'm curious about the best way to have my Login view "redirect" to the proper dashboard view based on the login credentials received. Ideally it would just check the kind of user and then pass the request on to the proper dashboard view without modifying it.

Upvotes: 1

Views: 308

Answers (1)

srowland
srowland

Reputation: 1705

You could simply use a conditional Django redirect from the shortcuts library? There are docs here for that.

Something like:

from django.shortcuts import redirect

def my_view(request):
    if something:
        return redirect('something-view')
    elif something_else:
        return redirect('something-else-view')
    else:
        # do something else

Of course you'd have to adapt this to the kind of view you are using (Class Based / Function Based).

You could also perform the switch with a query parameter if you want to use the same urls and views:

def my_view(request):
    if something:
        return redirect('something-view', type='thing')
    elif something_else:
        return redirect('something-view', type='else')
    else:
        # do something else

Then test for type in your something-view. It's not very secure of course (the user could change the type parameter), so you'd want to check what type of user they were again within the something-view to make sure they weren't trying to see the version they shouldn't.

And finally, option three is to redirect them both to the same dashboard, and they rely solely on a check of the user's type within the dashboard view to determine what content is shown to them. This is the most secure option, as the logic is kept on the server and out of the users' control :). This is also a very common idiom for views, for example, many views behave differently if there is a current user or not.

Upvotes: 2

Related Questions