Django:20 个 html 文件:需要 20 个 TemplateView 和 20 个 URL 模式?

标签 django

我有 20 个 Django 简单的“foo.html”模板文件。

我需要 20 个 TemplateView 和 url_patterns 中的 20 个条目吗?还是有更简单的解决方案?

最佳答案

使用 Django 2.1 和基于类的 View ,您的 urls.py 应该如下所示:

from django.urls import path

from your_app import views

app_name = 'your_app'

urlpatterns = [
    path('foo/<str:name>/', views.Foo.as_view(), name='foo'),
]

你的views.py是这样的:

from django.views import generic


class Foo(generic.TemplateView):

    def get_template_names(self)
        name = self.kwargs.get('name')
        # compute the template you want, for the example, I just take the name
        template_name = f'your_app/{name}.html'
        return [template_name]

仅此而已;)

关于Django:20 个 html 文件:需要 20 个 TemplateView 和 20 个 URL 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53188920/

相关文章:

Django-Wagtail - 将模型添加到内容面板时如何选择 "Choose A Page"面板?

python - create() 需要 1 个位置参数但给出了 2 个?

python - django如何使从bash执行的python脚本将stdout写入文件?

python - Django - modelform不保存图像

django - 使 Django 内置 send_mail 函数默认使用 html

djangorest框架m2m更新方法

python - Django 查询日期时间

python - 如何从 django 中的低级缓存 API 中删除特定键

python - Django ajax上传图片

django - 使用 Zappa 将 Geo Django 项目添加到 AWS Lambda。获取操作系统错误 : cannot open shared object file: No such file or directory