I have 20 Django simple "foo.html" template files.
Do I need 20 TemplateViews and 20 entries in url_patterns
or is there a simpler solution?
Using Django 2.1 and class-based views, your urls.py
should be like this:
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'),
]
And your views.py
like this:
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]
And that's all ;)
You can have a path like path('pages/<str:page>, views.pages)
And then in the view do something similar to:
from django.template.loader import get_template
from django.template import TemplateDoesNotExist
def pages(request, page):
template_name = f'your-app/{page}.html'
try:
get_template(template_name)
return render(request, template_name)
except TemplateDoesNotExist:
# returns 404
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With