http - Merging django url patterns with numeric id or name -


i'm implementing web service (no html, no templates, json) django , i'd able merge url patterns code doesn't repeat itself.

this urls need supported:

host/players/12/  returns player's  12  info host/players/me/  returns logged player info 

the 2 return same if logged player has id 12. need support more urls like:

host/players/12/other-stuff/ host/players/me/other-stuff/ 

how avoid having 2 different view methods /other-stuff/?

this have far:

instance_url_patterns = patterns('',     url(r'^$',            instance_with_id),     url(r'^other_stuff$', other_stuff_with_id),     # more suff goes in here )  current_instance_url_patterns = patterns('',     url(r'^$',            instance_without_id),     url(r'^other_stuff$', other_stuff_without_id),     # more suff goes in here )  players_url_patterns = patterns('',     url(r'^$',           show_list),     url(r'^(?p<pk>\d+)', include(instance_url_patterns)),     url(r'^me/$',        include(current_instance_url_patterns)), )   # origin of above urls (located in urls.py) urlpatterns = patterns('',     url(r'^players/',       include(players.relation_url_patterns)), ) 

notice how need have urls twice in instance_url_patterns , current_instance_url_patterns , methods implementations.

is there way merge/improve this?

to avoid duplicating view functions, use single view function default value of none pk, , bind logged in user's pk if it's none. see example in url dispatcher docs

assuming players instances of default auth's user model, simplified version this:

views.py def player_info(request, pk=none):     if pk none:         player = request.user     else:         player = get_object_or_404(user, pk=int(pk))     # stuff player  urls.py players_url_patterns = patterns('',     url(r'^$',           show_list),     url(r'^(?p<pk>\d+)/$', player_info),     url(r'^me/$',        player_info), ) 

you have specify patterns want bind view, don't need 2 different views default current user if no 1 else specified.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -