Search code examples
djangourlhyperlinkslug

Having issues with getting slugs to work correctly in urls.py


I am having an issue (probably cause by my lack of knowledge on the subject) with using slugs in my urls.py.

Urls.py
url(r'^admin/', include(admin.site.urls)),
url(r'^search_form/$', search_form),
url(r'^search/$', search),
url(r'^search_results/$', search_results),
#url(r'^search/search_results/acetic-acid/$', item),
url(r'^(?P<slug>[-\w\d]+),(?P<id>\d+)/$', item),

here is the html link href="search_results/{{chemical.S_field}}/">{{ chemical.Barcode }} where chemical.S_field slug field based off of the slugified version of an item name.

I am trying to create one page,url,and view that will be able take the user to a template that will change depending on what link they clicked on.

For example if you have hairy dogs, hairy cats, fluffy birds. If the user clicks on hairy cats the slug will be hairy-cats and the user will be taken to a page(search/search_results/hairy-cats/ that will have the various information on hairy cats that will be displayed from a database.

I feel that this is something that is possible but every time I try to use the slug (maybe I am doing it incorrectly) it displays ^(?P[-\w\d]+),(?P\d+)/$ as opposed to the information stored in the slug.

Also is there a place that has tutorial or good information on django similar to this? I have went through the django tutorials on the site and also the django tutorials in the Definitive Guide to Web Development with Django.

Thanks,

EDIT I may not have been clear before should have chosen a better example. the page that I would like to be displayed will be located at search/search_results/slug Where the slug will be the slugified version of the item's name. Here is what I am getting now with the addition of the newest url

Using the URLconf defined in Inventory.urls, Django tried these URL patterns, in   this order:

^admin/doc/
^admin/
^search_form/$
^search/$
^search_results/$
^(?P<slug>[-\w\d]+),(?P<id>\d+)/$
^(?P<slug>[-\w]+)/(?P<id>\d+)/$

The current URL, search/search_results/acetic-acid/, didn't match any of these.

Solution

  • This url pattern is invalid. You can read more about it in Named Groups

    url(r'^(?P<slug>[-\w\d]+),(?P<id>\d+)/$', item)
    

    Try

    url(r'^(?P<slug>[-\w\d]+)/$', item)
    

    Since you are trying to match only slugs.

    If you want to be able to match either slugs, or IDs, you can have 2 separate targets and each is a Named URL Pattern

    url(r'^(?P<id>\d+)/$', item, name='by-id')
    url(r'^(?P<slug>[-\w\d]+)/$', item, name='by-slug')