我有 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/