简体   繁体   中英

Slug Url Regex in Django

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM