Django url 路径转换器无法在生产环境中运行

Django url path converter not working in production

我在我的 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)