Slug Url Regex in Django

戏子无情 提交于 2019-12-04 11:35:29

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/13886944/slug-url-regex-in-django

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!