D
D
Dmitry Astrikov2014-03-30 05:01:12
Django
Dmitry Astrikov, 2014-03-30 05:01:12

Is it possible to create urlpatterns dynamically in django?

The problem is this: there is a service where users can create their own sites. Each site is accessible by a domain name like site1.app.com, site2.app.com, etc. Users can create arbitrary pages with arbitrary URLs on their sites.
I want to dynamically create a routing scheme in my application, depending on which subdomain the request came to. Those. roughly speaking, I need to understand which subdomain the request came to, pull out all the pages created for this subsite from the database and create urlpatterns according to these pages.
Is this even possible, or dig in the direction of one universal view-router?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
stepank, 2014-03-30
@astrikovd

It seems that in your case it is enough to create a url pattern like this:

urlpatterns = patterns('',
    ...
    url(r'^pages/(.*)', page_dispatcer),
)

The handler will have the following arguments:
def page_dispatcher(request, path):
    ...

Next, in page_dispatcher, you need to look at request.META['HTTP_HOST'] to get the domain name from which to pick out the subdomain. By subdomain, find the pages of the desired user and then select the desired one along the path.
I can assume that the set of pages for the user does not change very often, therefore, of course, it is not advisable to go into the database for a list of pages for each request. To avoid this, query results can be cached. How exactly to do this depends on your project.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question