Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: 20 html files: 20 TemplateViews and 20 URL patterns needed?

Tags:

django

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?

like image 385
guettli Avatar asked Nov 07 '18 11:11

guettli


2 Answers

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 ;)

like image 173
mistiru Avatar answered Nov 15 '22 09:11

mistiru


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
like image 25
grouchoboy Avatar answered Nov 15 '22 09:11

grouchoboy