Login

Routing urls.py By Convention

Author:
doconix
Posted:
June 1, 2012
Language:
Python
Version:
1.4
Score:
0 (after 0 ratings)

No more entries in urls.py...

This is the simple version of a central controller for an app that routes requests by names, thus keeping you from adding a line into urls.py for every, single, page.

Assuming your app name is "account", add the following to your urls.py file:

(r'^account/(?P<path>.*)\.dj(?P<urlparams>/.*)?$', 'account.views.route_request' )

The URL /account/mypage.dj will be routed directly to account.views.py -> process_request__mypage(request, parameters).

You can read more about this on my blog.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
# place this snippet in your app's views.py file.
# it assumes your app is called 'account', so change below as needed

import sys
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response
def route_request(request, path, urlparams):
  parameters = urlparams and urlparams[1:].split('/') or []
  funcname = 'process_request__%s' % path
  try:
    function = getattr(sys.modules[__name__], funcname)
  except AttributeError:
    return render_to_response('account/%s.dj' % path, { 'parameters': parameters })
  return function(request, parameters)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.