我目前有一个基于用户输入的列表名称的网址。列表名称。一切查询和显示都没有问题。但是,当用户输入空格作为列表名称时,浏览器不能很好地处理它。我意识到我需要对字符串进行 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
Run Code Online (Sandbox Code Playgroud)
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)
Run Code Online (Sandbox Code Playgroud)
url(r'^user/(?P<username>\w+)/list/(?P<listname>\w+)/$', mylistpage, name='lists'),
Run Code Online (Sandbox Code Playgroud)
URL 中的空格不是一个好主意。\n此用例是典型的候选用例SlugField
\n\n\nslug 是某事物的简短标签,仅包含字母、数字、下划线或连字符。它们\xe2\x80\x99通常用在URL中
\n
所以基本上,在您的模型中,您将添加另一个名为 的字段slug,并将其传递到 URL 中。
您可以使用一个现成的软件包django-autoslug来自动生成 slugs。
以下是一些可能会提供有关蛞蝓的更多见解的帖子:
\n\n\n| 归档时间: |
|
| 查看次数: |
2159 次 |
| 最近记录: |