Django: transferring data to view from the URL manager without including data in the url?

I decided to set up dynamic URL creation in Django based on the names stored in the database objects. All of these pages should be handled by the same view, but I would like the database object to be passed to the view as a parameter when it is called. Is it possible?

Here is the code I have:

places = models.Place.objects.all()
for place in places: 
    name = place.name.lower()
    urlpatterns += patterns('',
        url(r'^'+name +'/$', 'misc.views.home', name='places.'+name)
    )

Is it possible to pass additional information to the view without adding additional parameters to the URL? Since the URLs are from the root directory, and I still need 404 pages to display other values, I can't just use the string parameter. Is there a solution to abandon attempts to add URLs to root, or is there another solution?

I assume that I could search by the name itself, since all URLs should be unique anyway. Is this the only option?

+5
source share
2 answers

This is usually a bad idea, as it will query the database for each query, not just queries related to this model. The best idea is to come up with a common url composition and use the same look for all of them. Then you can get the appropriate place in the view, which gets into the database only when this particular view is reached.

For instance:

urlpatterns += patterns('',
    url(r'^places/(?P<name>\w+)/$', 'misc.views.home', name='places.view_place')
)

# views.py
def home(request, name):
    place = models.Place.objects.get(name__iexact=name)
    # Do more stuff here

I understand that this is not what you really requested, but should provide you with much less headaches.

+18
source

, , :

url(r'^'+name +'/$', 'misc.views.home', {'place' : place}, name='places.'+name)

, .

+18

All Articles