Full-stack web applications developer

Request specific URLs in Django

September 17, 2015Arthur Pemberton0 Comments

Do you have a need to use different URL pattern sets based on specifics of an HTTP request? Recently, I needed to choose from a predefined URL pattern (ie. URLConf module) based on the domain name of the request, ie. HTTP_HOST. The URL patterns themselves are not dynamically set, just dynamically chosen.

By default, the URL dispatcher in Django finds the URLConf module via the ROOT_URLCONF setting. However, it will also check the HTTPRequest for a urlconf property, ie. request.urlconf.

The challenge now is to set urlconf on the request, and this needs to be done via custom middleware. The logic you employ to choose the URLConf module is entirely up to you, but here is a simple same middleware that sets the urlconf property.

class UrlMiddleware(object):

	def process_request(self, request):
		# choose urlconf
		urlconf = 'myapp.mysubapp.urls'
		# add it to the request
		request.urlconf = urlconf


Remember to add the middleware to Hope this helps someone.

Leave a Reply