Skip to content

Commit

Permalink
Merge pull request #89 from bartmika/master
Browse files Browse the repository at this point in the history
Added reverse for tenants. #87
  • Loading branch information
tomturner committed Oct 13, 2016
2 parents 7020e63 + e57507d commit 0c1c137
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions django_tenants/models.py
@@ -1,6 +1,8 @@
from django.conf import settings
from django.db import models, connection, transaction
from django.core.management import call_command
from django.contrib.sites.shortcuts import get_current_site
from django.core.urlresolvers import resolve, reverse

from .postgresql_backend.base import _check_schema_name
from .signals import post_schema_sync, schema_needs_to_be_sync
Expand Down Expand Up @@ -145,6 +147,16 @@ def get_primary_domain(self):
except get_tenant_domain_model().DoesNotExist:
return None

def reverse(self, request, view_name):
"""
Returns the URL of this tenant.
"""
url = 'https://' if request.is_secure() else 'http://'
url += str(self.schema_name) + '.'
url += get_current_site(request).domain
url += reverse(view_name)
return url


class DomainMixin(models.Model):
"""
Expand Down
9 changes: 9 additions & 0 deletions dts_test_project/customers/models.py
Expand Up @@ -7,6 +7,15 @@ class Client(TenantMixin):
description = models.TextField(max_length=200, blank=True, null=True)
created_on = models.DateField(auto_now_add=True)

def reverse(self, request, view_name):
"""
If you have different implementation of reserve from what the
Django-Tenants library uses (A.k.a. Sites Framework) then you can write
your own override here.
"""
# Write your own custom code else use existing code.
return super( Client, self ).reverse(request, view_name)


class Domain(DomainMixin):
pass

1 comment on commit 0c1c137

@nftchance
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For anyone curious to redirect to a different tenant you will do:
return redirect(target_tenant.reverse(request, 'view_name'))

Yes, it's right above in the commit, but I searched for this for far too long so I figured it'd be best to include here :)

Use Case:
You allow the users to log in on the public tenant and want to direct to their personal tenant URL on authentication of the user. You just need to retrieve the object of the target_tenant and get the reverse of it. Rather simple though it flew over my head for a few minutes.

Thank you for this addition, was really helpful!

Please sign in to comment.