开发者

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开发者_如何学Go 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 %}


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

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


In your template, assuming post is an instance of your model:

{% url single_post post.slug %}

Your url regex should look like the following:

url(r'^post/(?P<slug>[\w-]+)/$', ...

To test the above regex, try to access a few posts directly in your browser with a variety of valid slugs and see if they works. Once this is done, start testing the url names.


A slug value can contain any a-z, A-Z, 0-9, _ and -. The first 3 are represented by the special character w and since - itself is a special character, we need to use represent them both using a backslash \. So the correct expression becomes

url(r'^post/(?P<slug>[\w\-]+)/$', ...

At least this is what is working in my case.


In Django 1.5 the slug validator uses this regex:

slug_re = re.compile(r'^[-a-zA-Z0-9_]+$')

See https://github.com/django/django/blob/stable/1.5.x/django/core/validators.py#L106

You can use this regex in urls.py:

url(r'^post/(?P<slug>[-a-zA-Z0-9_]+)/$', ...

In earlier versions it was [-\w]+ but I guess in Python3 \w matches non ascii characters like umlauts.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜