Search code examples
djangodjango-templatesslug

Whats the correct way to use and refer to a slugfield in a django 1.3


Whats the correct way to use and refer to a slugfield in a django 1.3

for example the following code should link via slug to a generic view however the NoReverseMatch error is received.

Caught NoReverseMatch while rendering: Reverse for 'single_post' with arguments '('', u'post-2')' and keyword arguments '{}' not found.

From my understanding this saying that the error lies in the template however being a newbie and having tried many different variations on {% url single_post slug=post.slug %} this may not be the case.

Could someone please explain why this is happening so that I can understand where the problem lies andhow to fix.

Ive tried {% url single_post slug=post.slug %},{% url single_post slug %}{% url single_post slug=post.slug %} and many other variations

All help is greatly appreciated

model

slug = models.SlugField(max_length=120, unique=True)

url

   url(r'^post/(?P<slug>[a-z-]+)/$', list_detail.object_detail,
         {'queryset': Post.objects.all(), 'template_object_name': 'post', 'slug_field': 'slug'}, name="single_post"),

template

{% url single_post slug post.slug %}

Solution

  • Your regex doesn't allow for numeric values. Try:

    (?P<slug>[\w-]+)