Django Templates

From https://wallpaperaccess.com/spaghetti-western

The emphasis on this page is to consider the directory structure with emphasis on the naming and location of the html template files. In my example I have two apps in the project, “certs” is about certificate records and “users” user records. So I have files to index, update, delete, view them both. I also of course have the calling views (functions) in the separate apps similarly named.

Django can let you name the templates what you want and leave them all in the top level templates directory if you like. But you have to think ahead if you do that. So you can’t bring in an app with an “update.html” file or an “update” view if you already are using those names. But if you organise them like this below you can refer to “certs/index.html” and a “users/index.html”. So no name conflict from the get go. You can also refer to the view like “certs:index” or “users:index” within your code and not worry about name clashes when calling views from your code or templates.

Django will actually search all the possible template directories and you can get name conflicts. So stay organised from the start and be a smart cowboy.

   [1]Django-WorkingDir/
     [2]manage.py
     [2]requirements.txt
     [2[templates/
        base.html
        copyright.html
     [2]certiffy-project/
          settings.py
          base.html
      [2]certs/
           view.py    
           urls.py
           models.py
           forms.py
           template/
             certs/
               index.html
               create.html
               update.html
               delete.html
      [2]users/
           views.py
           urls.py
           models.py
           forms.py
           template/
             users/
               index.html
               create.html
               update.html
               delete.html

So you might have your views (your web functions) like this within your view.py file.

def index(request):
def search(request):
def create(request):
def detail(request, id):
def update(request, id):
def delete(request, id):

I tend to write one app for each data entity but that is a matter of choice. In a small app it would be fine to just be more organised and mix them into one e.g. certs-index() and certs-index.html vs users-index() and users-index.html.

Your urls.py file can look pretty standard too. In this example the only thing odd thing is that certs is the default main page so the path is “”.

urlpatterns = [
    path("", views.index, name="index"),
    path("search/", views.search, name="search"),
    path("create/", views.create, name="create"),
    path('detail/<id>', views.detail, name="detail"),
    path('update/<id>', views.update, name="update"),
]

Leave a Reply

Your email address will not be published. Required fields are marked *