Django中的lug lug lug l [英] Slug Url Regex in Django

查看:104
本文介绍了Django中的lug lug lug l的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读了很多关于正确使用s lug从对象列表创建详细信息视图之后。但是,我仍然有问题让它为我工作。我在我的模板中显示对象列表,如:

  {%for thing in thing_list%} 
< div class ='thing-detail'>< a href ='{%url detail%}'>< img src ='theimage.png'/>
{%endfor%}

但是我得到一个 NoReverseMatch 错误细节



我认为我的正则表达式有问题,或者只是一个更好的方法,我失踪了。



正则表达式:

  url(r'^ thing /(?P< slug> [\w - ] +)/ $','views.detail',name ='detail'),

查看:

  def detail(request,slug):
thing = get_object_or_404(Thing,slug = slug)
return render(request,'detail.html',{'thing':thing})

型号:

  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()

谢谢你ping!

解决方案

你没有传递任何参数来构建 detail 网址。你可能想这样做:

  {%urldetailthing.slug%} 

哪些将创建一个详细信息 URL,并填入给定的插槽。 >

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.

这篇关于Django中的lug lug lug l的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆