gpt4 book ai didi

Django URL 基于带有空格的 charfield?

转载 作者:行者123 更新时间:2023-12-03 09:21:11 30 4
gpt4 key购买 nike

我目前有一个基于用户输入的列表名称的网址。列表名称。一切查询和显示都没有问题。但是,当用户输入空格作为列表名称时,浏览器不能很好地处理它。我意识到我需要对字符串进行 slugify,但不知道如何进行此实现。我有一种感觉,我向模型添加了某种 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(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'),

最佳答案

URL 中的空格不是一个好主意。此用例是 SlugField 的典型候选者。

A slug is a short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs

基本上,在您的模型中,您将添加另一个名为 slug 的字段,并将其传递到 URL 中。

您可以使用名为 django-autoslug 的现成软件包自动生成段头。

以下一些帖子可能会提供有关鼻涕虫的更多见解:

关于Django URL 基于带有空格的 charfield?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30407478/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com