[Answer]-Django 2 different views in 2 different apps for same URL

0πŸ‘

βœ…

I would create a third view that only checks the user’s status and then calls the right view:

import A.views
import B.views

def combined_index(request, *args, **kwargs):
    """Call A.views.index if user is authenticated, otherwise B.views.index."""
    if request.user.is_authenticated():
        return A.views.index(request, *args, **kwargs)
    else:
        return B.views.index(request, *args, **kwargs)

If you want to make this optional based on whether B is in INSTALLED_APPS, simply do:

import A.views

from django.conf import settings

if 'B' in settings.INSTALLED_APPS:
    import B.views
    def combined_index(...):
        # as above
else:
    combined_index = A.views.index
πŸ‘€RemcoGerlich

1πŸ‘

Several ways :

  • Use same view and check if user is authenticated or not in the beginning of view.
  • create dummy view. Create view decorator to use before this dummy view. In decorator check if user is authenticated or not and then return one of two views from decorator
  • Use same view, just give one additional parameter to the view – template. And render different templateto different users.
πŸ‘€Odif Yltsaeb

0πŸ‘

Use same view and check if user is authenticated or not in the beginning of view.

I think this is a natrual solution.

def login_view(request):
result = get_response_code('success')

# POST means user is logging in
if request.method == 'POST':
    username = request.POST.get('username', '')
    password = request.POST.get('password', '')
    next = request.GET.get('next', '')
    user = auth.authenticate(username=username, password=password)
    if user and user.is_active:
        logger.info('Authenticate success for user ' + username)
        # Correct password, and the user is marked "active"
        auth.login(request, user)
        if next:
            return redirect(next)
        else:
            return redirect('/admin')
    else:
        logger.info('Authenticate failed for user ' + username)
        result = get_response_code('auth_failed_invalid_username_or_password')
# Just show the login page
return render_to_response('account/login.html',
                          locals(),
                          context_instance=RequestContext(request))
πŸ‘€lethe3000

Leave a comment