0

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 :)

4
  • I wouldn't call those sub-urls, and you may want to look at named groups or capturing text in urls. Commented Jul 27, 2011 at 21:00
  • do all the views need to be unique views or can you just pass the do_a part of www.example.com/ajax/do_a to the same view? Commented Jul 27, 2011 at 21:04
  • @j_syk I don't understand your question Commented Jul 27, 2011 at 21:27
  • ok, let's you have a url of do_a, and your view is ajax.do_a, and also another url of do_b and view ajax.do_b. Do ajax.do_a and ajax.do_b do the same thing except use different data? or do the view functions need to be completely different. If they do the same thing, just with different inputs and outputs, I think Jack's answer should help. Commented Jul 27, 2011 at 21:44

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.