After reading a lot about proper use of a slug to create a detail view from a list of objects. However, I am still having problems getting it to work for me. I am displaying a list of objects in my template like:
{% for thing in thing_list %}
<div class='thing-detail'><a href='{% url detail %}'><img src='theimage.png' />
{% endfor %}
But am getting a NoReverseMatch
error on detail
.
I figure that there is either something wrong with my regex, or there is just a better way of doing this that I am missing.
Regex:
url(r'^thing/(?P<slug>[\w-]+)/$', 'views.detail', name='detail'),
View:
def detail(request, slug):
thing = get_object_or_404(Thing, slug=slug)
return render(request, 'detail.html', {'thing': thing})
Model:
class Thing(models.Model):
user = models.ForeignKey(User)
created_on = models.DateTimeField(auto_now_add=True)
slug = models.SlugField()
def save(self, **kwargs):
slug = '%s' % (self.user)
unique_slugify(self, slug) ## from http://djangosnippets.org/snippets/1321/
super(Thing, self).save()
Thank you for helping!
You're not passing any arguments to build the detail
URL. You probably want to do this:
{% url "detail" thing.slug %}
Which will create a detail
URL with the given slug filled in.