aerain
aerain

Reputation: 591

Handling multiple sub-urls in Django's url.py file

In my djang urls pattern file, I'd like to hold a bunch of sub-url's but I don't want to make it ugly.

I have a file which handles all of my Ajax requests (it outputs different JSON files depending on the request it gets.

example (in my url.py): in the form: (url, maps to) (ajax/do_a, ajax.do_a) ajax/do_b, ajax.do_b) ajax/do_c, ajax.do_c) ajax/do_d, ajax.do_d)

these are all sub-urls, eg. mywebsite.com/ajax/do_a mywebsite.com/ajax/do_b etc.

Basically do_a,do_b,do_c,and do_d are all different request handlers sitting in the same same in the "ajax.py" file. I really don't want to be filling up my urls.py file with all of these urls for ajax requests. I was thinking of move this so that I only have ajax/ in my url.py file and then somehow parse the ajax/ request url in my request handler (in the ajax.py file) so I can see what string came after the "ajax/". I'm not sure how to do this or if this would be a good idea to do this....Could anyone offer some advice? thanks :)

Upvotes: 0

Views: 407

Answers (1)

Jack M.
Jack M.

Reputation: 32070

You could set up a dispatcher view for handling these. For example, in your urls.py:

(r'^ajax/do_(?P<do_token>(\d+))/$', 'do_dispatcher', {}, "di_dispatcher"),

Then, give yourself a view to handle it:

def do_a(request):
    pass
def do_b(request):
    pass
def do_c(request):
    pass

DO_LOOKUP = {
    'a' = do_a,
    'b' = do_b,
    'c' = do_c,
}

def do_dispatch(request, do_token):
    do_func = DO_LOOKUP.get(do_token, None)
    if do_func is None:
        return HttpResponseNotFound("No do could be found for token '%s'!" % do_token)
    else:
        return do_func(request)

Upvotes: 1

Related Questions