python - Django multi tenancy -
tl; dr: there way override default behaviour of reverse
?
in django project have alot of urls such as
url(r'^\w+/company/', include("company.urls", namespace="company")),
which allows urls such as
.../companya/company/ .../companyb/company/
so can use custom middleware modify request include specific details based upon company using site
this works fine except when django trying decipher full path reverse
, {% url .. %}
...
it seems returning /x/company/
default match regex. since django.utils.regex_helper
method next_char
has escape mapping \w
map x
the url
tag have been able override replace /x/
correct company name , wondering if there similar thing can override reverse
in same way, or else can resolve problem?
previously, using
url(r'^(?p<company_name>\w+)/company/', include("company.urls", namespace="company"))
but meant had include parameter in every view
def view(request, company_name): ...
as include in other calls view (i.e {% url %}
) trying avoid.
for ease of use, django packages compiled page full of every possible existing django package can accomplish this. below own simple implementation
i modified nginx proxy config use following
server_name ~(?<short_url>\w+)\.domainurl\.com$; ... stuff related static files here location / { proxy_set_header x-customurl $short_url; .... other proxy settings }
what create variable inside request header can used within django. variable used within custom middleware extend request reference model allows use anywhere.
class companymiddleware(object): def process_request(self, request): if settings.debug: request.company = companyclass.objects.get(id=1) return none short_url = request.meta.get("http_x_customurl") try: company = companyclass.objects.get(short_url=short_url) except model.doesnotexist: return httpresponsebadrequest('company not found') request.company = company return none
examples:
www.companya.domainurl.com # short_url companya test.domainurl.com # short_url test
to use within template, context processors must added settings.py
template_context_processors = ( "django.contrib.auth.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", 'django.core.context_processors.request' # 1 in particular )
Comments
Post a Comment