简体   繁体   中英

Add all the templates to urls.py url_patterns in django

I have a lot of templates in my project. I want to add them to urls.py without typing each one of them. I want to loop them in my url_patterns. Is there any way I can add all my templates in the urls.py?

After doing some brainstorming, I found a way to loop through my template folder and add all the files to the url_pattern. After your url_patterns, get your list of templates using os.listdir() method. Then simply iterate them, add them in route and lastly append in the url_patterns.

import os
from core.settings import BASE_DIR
from django.contrib import admin
from django.urls import path, include
from django.views.generic import TemplateView


urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('snippets.urls')),
]

dir = os.path.join(BASE_DIR, 'templates')
file_list = os.listdir(dir)
for file in file_list:
    path_url = file.replace('.html', '/')
    name = file.replace('.html', '')
    route = path(path_url, TemplateView.as_view(template_name=file),
                        name=name)
    urlpatterns.append(route)

hope this helps:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM