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

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

问题描述

为什么我生成的s s ur do are are are are are are???????????????>>>>>>>>> are are are are are are are are are are are are are当我在终端上打印出来时,正确地生成,但是我不知道为什么url有额外的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b

某些地方有些错误,但我似乎无法发现



在我看来,我使用< a href ={ group.get_absolute_url}}> ... 得到s子。现在,这个工作,但是输出上述问题。如果我执行 href ={%url'group'group.slug%} ,则会抛出一个无法找到反向匹配的错误。



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



在urls.py

  (r'^ / group /(?P< slug> [ -  \w\d] +)/ $',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 BlogGroupFor m(forms.ModelForm):


def __init __(self,* args,** kwargs):

super(BlogGroupForm,self) 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)
返回truncate_slug(实例,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]

在itertools.count(1)中:
如果不是arg .objects.filter(SLU g = instance.slug).exists():
break
instance.slug =%s-%d%(original_slug [:length - len(str(x))-1],x )
instance.save()
返回实例


解决方案

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

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

请注意,我还有




  • 已删除 \d ,因为 \w
  • 已使用 url()(Django 1.8+的最佳做法),并命名为url模式。这应该希望使用 {%url%} 标签工作来反转网址。在您的模板中使用 group.get_absolute_url ,但是,如果您不想使用URL标签,则不需要使用。


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

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

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.

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

in urls.py

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

model

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

form

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

解决方案

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"),

Note that I have also

  • 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中渲染的s are不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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