Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

url

django

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?

like image 329
Herman Schaaf Avatar asked Jan 16 '11 23:01

Herman Schaaf


People also ask

What happens if you skip the trailing slash in Django?

The local Django webserver will automatically restart to reflect the changes. Try again to refresh the web page for the User section of the admin without the trailing slash: 127.0. 0.1:8000/admin/auth/user .

Which method is used instead of path () in URLs py to pass in regular expressions as routes?

To do so, use re_path() instead of path() . In Python regular expressions, the syntax for named regular expression groups is (?P<name>pattern) , where name is the name of the group and pattern is some pattern to match.

What is the difference between path and URL in Django?

In Django 2.0, you use the path() method with path converters to capture URL parameters. path() always matches the complete path, so path('account/login/') is equivalent to url('^account/login/$') . The part in angle brackets ( <int:post_id> ) captures a URL parameter that is passed to a view.


1 Answers

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.

like image 184
Marcio Cruz Avatar answered Oct 22 '22 10:10

Marcio Cruz