Gustavo Gil
Gustavo Gil

Reputation: 3

One url for two different views

I'm developing a site that have two types of User, and the project's owners want two different home (templates) after the user is authenticated, so, I tried this:

url

# home a
url(r'^home/$', HomeAView.as_view(), name='home-a'),
# home b
url(r'^home/$', HomeBView.as_view(), name='home-b'),

And some like that at into my log_in view:

if user.typeUser == "HA":
    print('Go to Home A')
    return redirect(reverse('sesion:home-a'))
else:
    print('Go to Home B')
    return redirect(reverse('sesion:home-b'))

So the problem is that after the user is authenticated, the site always go to the first url! (Home A) I printed by console a little flag and the conditional is working, and pass by sesion:home-a or home-b, but always go to home-a. Why reverse don't resolve the url, if I assigned different names? Can't I have one url for two views??

Thanks for your help, I'm working on Django 1.7

Upvotes: 0

Views: 3563

Answers (2)

Nnaobi
Nnaobi

Reputation: 429

For those looking for a class based view implementation, you can override the get_template_names method for any view that inherits the TemplateResponseMixinand return a list of strings. The template names will be searched in that order until one matches or ImproperlyConfigured is raised

class Home(TemplateResponseMixin):
   ...
   def get_template_names(self):
      if self.request.user.typeUser == "HA":
         return ['template_a.html']
      else:
         return ['template_b.html']

Upvotes: 0

dukebody
dukebody

Reputation: 7185

No, you cannot have two different views for the same URL. Django decides which view function to use according to the URL and the routes defined.

Use custom code inside an unique view to render a different template depending on the type of user:

def home(request):
    if user.typeUser == "HA":
        render(request, 'template_a.html')
    else:
        render(request, 'template_b.html')

Upvotes: 4

Related Questions