Django: Passing data to view from url dispatcher without including the data in the url?

19,058

Solution 1

That's generally a bad idea since it will query the database for every request, not only requests relevant to that model. A better idea is to come up with the general url composition and use the same view for all of them. You can then retrieve the relevant place inside the view, which will only hit the database when you reach that specific view.

For example:

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 realize this is not what you truly asked for, but should provide you with much less headaches.

Solution 2

I think you can pass a dictionary to the view with additional attributes, like this:

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

And you can change the view to expect this parameter.

Share:
19,058
Herman Schaaf
Author by

Herman Schaaf

Software engineer (Go, Python, JavaScript, Java, C++) currently working on data pipeline and machine learning applications at Skyscanner. hermanschaaf.com

Updated on July 26, 2022

Comments

  • Herman Schaaf
    Herman Schaaf almost 2 years

    I've got my mind set on dynamically creating URLs in Django, based on names stored in 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 that possible?

    Here is the code I currently 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 extra information to the view, without adding more parameters to the URL? Since the URLs are for the root directory, and I still need 404 pages to show on other values, I can't just use a string parameter. Is the solution to give up on trying to add the URLs to root, or is there another solution?

    I suppose I could do a lookup on the name itself, since all URLs have to be unique anyway. Is that the only other option?

  • Herman Schaaf
    Herman Schaaf over 13 years
    That's what I asked for - didn't know that's how one does it. @Cide raised a good point that this would require a database query for every request, so I'm going with his answer. Thanks!
  • Marcio Cruz
    Marcio Cruz over 13 years
    No problem, glad you found a solution :)