Django url 路径转换器在生产中不起作用

问题描述

我在我的 django 应用程序中使用路径转换器,如下所示:

# urls.py

from . import views
from django.urls import path

urlpatterns = [
  path('articles/<str:collection>',views.ArticleView),]


# views.py

@login_required
def ArticleView(request,collection):
    print(collection)
    if collection == "None":
        articles_query = ArticleModel.objects.all()
    ...

这在 url 开发中工作正常,因为:http://localhost:8000/articles/My Collection 被编码为 http://localhost:8000/articles/My%20Collection,并在 ArticleView 中正确解码。但是,在开发中,我必须像这样编辑视图才能使其工作:

# views.py

import urllib.parse

@login_required
def ArticleView(request,collection):
    collection = urllib.parse.unquote(collection)
    print(collection)
    if collection == "None":
        articles_query = ArticleModel.objects.all()
    ...

否则,print(collection)显示 My%20Collection,而视图其余部分的整个逻辑将失败。

requirements.txt

asgiref==3.2.10
Django==3.1.1
django-crispy-forms==1.9.2
django-floppyforms==1.9.0
django-widget-tweaks==1.4.8
lxml==4.5.2
Pillow==7.2.0
python-pptx==0.6.18
pytz==2020.1
sqlparse==0.3.1
XlsxWriter==1.3.3
pyMysqL

在这里做错了什么? 提前致谢!

解决方法

正在对 URL 进行 urlencoded,将空格编码为 %20。还有许多其他编码。正如您发现的那样,您需要对该参数进行解码,以便将其与您期望的进行比较。正如您可能已经意识到的那样,如果您有一个真正想要 The%20News 而不是 The News 的值,则您没有追索权。为了处理这种情况,人们将创建一个 slug 字段。 Django has a model field for this in the framework.

这通常是记录的 URL 友好的唯一值。

假设您将 slug = models.SlugField() 添加到 ArticleModel,您的网址和视图可以更改为:

urlpatterns = [
  # Define a path without a slug to identify the show all code path and avoid the None sentinel value.
  path('articles',views.ArticleView,name='article-list'),path('articles/<slug:slug>' views.ArticleView,name='article-slug-list'),]


@login_required
def ArticleView(request,slug=None):
    articles_query = ArticleModel.objects.all()
    if slug:
        articles_query = articles_query.filter(slug=slug)