url django 中渲染的 slugs 不正确 [英] rendered slugs are not correct in url django

查看:27
本文介绍了url django 中渲染的 slugs 不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我生成的 slugs url 中总是有一个额外的 %2F?

Why do I always have an extra %2F in my generated slugs urls?

当我在终端中打印它们时,下面的所有 slug 都正确生成,但我不知道为什么 url 有额外的 %2F

All the slugs are generating correctly below when I print them out in the terminal, but I don't know why the url has the extra %2F

某处有问题,但我似乎无法发现

Something is wrong somewhere but I cannot seem to spot it

在我看来,我正在使用 ... 来获取 slug.现在,这可行,但会输出上述问题.如果我这样做 href = "{% url 'group' group.slug %} 这会抛出一个错误,它找不到反向匹配.

In my view i am using <a href = "{{ group.get_absolute_url }}">... to get the slug. Now, this works but outputs the above problem. If i do href = "{% url 'group' group.slug %} this throws an error that it can't find a reverse match.

示例:组的标题是 a group url 将是 ../%2Fgroup/a-group/

Example: title of group is a group the url will be ../%2Fgroup/a-group/

在 urls.py

 (r'^/group/(?P<slug>[-wd]+)/$', "group"),

型号

class BlogGroup(models.Model):

    title = BleachField()
    image = models.ImageField(upload_to="uploads/group_images", default="uploads/group_images/none/none.jpg")
    created = models.DateTimeField(default = datetime.now)
    slug = models.SlugField(unique = True)

    def __str__(self):

        return self.title 

    def get_absolute_url(self):
        return reverse("blog.views.group", kwargs = {'slug':self.slug})

表格

class BlogGroupForm(forms.ModelForm):


    def __init__(self, *args, **kwargs):

        super(BlogGroupForm, self).__init__(*args, **kwargs)
        self.fields["title"].requried = True
        self.fields["image"].required = True
        self.fields["title"].widget = forms.TextInput()

    class Meta:
        model = BlogGroup
        fields = ["title", "image", "slug"]

    def save(self, commit = False):

        instance = super(BlogGroupForm, self).save(commit = False)
        return truncate_slug(instance, BlogGroup)

utils.py

from django.utils.text import slugify
import itertools

def truncate_slug(instance, arg):

    length = arg._meta.get_field('slug').max_length
    instance.slug = original_slug = slugify(instance.title)[:length]

    for x in itertools.count(1):
        if not arg.objects.filter(slug = instance.slug).exists():
            break
        instance.slug = "%s-%d" % (original_slug[:length - len(str(x)) -1], x)
    instance.save()
    return instance

推荐答案

您在正则表达式的开头有一个正斜杠.如果你删除它,它应该阻止 %2f(注意 %2f 是一个 url 编码的正斜杠).

You have a forward slash at the beginning of your regex. If you remove it, it should prevent the %2f (note that %2f is a url encoded forward slash).

url(r'^group/(?P<slug>[-w]+)/$', "group", name="group"),

注意我也有

  • 删除了 d,因为 w 已经包含数字 0-9
  • 使用 url()(Django 1.8+ 的最佳实践)并命名 url 模式.这应该有望使使用 {% url %} 标签反转 url 工作.不过,在模板中使用 group.get_absolute_url 没问题,如果您不想使用 url 标记,则无需使用.
  • removed d, since w already includes digits 0-9
  • used url() (best practice for Django 1.8+) and named the url pattern. That should hopefully make reversing the url with the {% url %} tag work. Using group.get_absolute_url in your template is fine though, there's no need to use the url tag if you don't want to.

这篇关于url django 中渲染的 slugs 不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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