Django URL基于带空格的charfield?

时间:2015-05-23 00:00:13

标签: django

我目前有一个基于用户输入列表名称的网址。列表名称。一切都查询并显示没有问题。但是,当用户输入空格作为列表名称时,浏览器不能很好地处理它。我已经意识到我需要对字符串进行细化,但我不确定如何进行此实现。我有一种感觉,我在模型中添加了某种slug字段,然后查询slug字段名称以将自身与呈现给页面的模型对象相关联。我只是不确定如何编码。

模型

class newlist(models.Model):
    user = models.ForeignKey(User)
    list_name = models.CharField(max_length = 100,)
    picture = models.ImageField(upload_to='profiles/', default = "/media/profiles/default.jpg")

    def __str__(self):
        return self.list_name

查看

def mylistpage(request, username, listname):


    context = RequestContext(request)
    #make sure that the user is authenticated
    if username == request.user.username:
        #If the user is authenticated, then perform the following functions to the page
        if request.user.is_authenticated():
            #Store the current user request object into a variable
            user = User.objects.get(username=username)

            #Store the list name to the item that starts with the url input
            listname = request.user.newlist_set.filter(list_name__iexact=listname)

            listitems = request.user.newlist_set.all()
            if not listname:
                return redirect('/notfound')
    else:
        return redirect('/notfound')

    return render_to_response('listview.html', {'lista': listname}, context)

URL

url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'),

1 个答案:

答案 0 :(得分:4)

网址中的空格不是一个好主意。 此用例是SlugField

的典型候选对象
  

slug是一种短标签,只包含字母,数字,下划线或连字符。它们通常用于URL

所以基本上,在你的模型中,你会添加另一个名为1950000.0 750000.0 1433000.0 1300000.0 2183000.0 1644736.0 的字段,并将其传递给URL。

您可以使用名为django-autoslug的现成软件包自动生成slu ..

以下是一些帖子,可能会提供更多关于slu的见解: