Rick
Rick

Reputation: 11

How do I separate my templates correctly in Django?

I'm in doubt as to how I can make my templates in Django. I created three apps on my django:

  1. User
  2. Posts
  3. Index

And each app I create a folder called "templates" and there I make the templates for these pages, but there is a problem! Whenever I put the same page in my view that I created in another template, all the repeated content appears there, is there any way to make this not happen?

Upvotes: 1

Views: 78

Answers (2)

Foot
Foot

Reputation: 449

Welcome Rick! There are a few ways to configure templates in Django. This answer is specific to defining templates within each app. Let's take that 'Posts' app for example.

Within the posts app folder, create a templates folder, and then create ANOTHER folder under templates called posts (should match the app name). So:

BASEDIR/
  > posts
    > templates
      > posts
        (store your posts templates/html files here)
        - show_post.html
        - posts.html
        etc, etc

Then when you call render in a view, it will look like:

def show_post(request, post_id):
  #-- your view logic here --#
  context = {'post': post }
  return render(request, 'posts/show_post.html', context)

The above render function will look for the template at posts/templates/posts/show_post.html.

For all of this to work, make sure you have APP_DIRS set to True in your settings.py file:

TEMPLATES = [
  { 
    'BACKEND': ...
    'DIRS': [],
    'APP_DIRS': True,   #<-- this line is key
    (etc, etc)
  }
]

As you add apps to your project, use the same structure as we did with Posts. And be sure to call the correct template in render in your view.

Like I said, there's more than one way to organize your Django templates, but this method has worked well for me on small and medium sized Django projects.

Upvotes: 1

Rayyan
Rayyan

Reputation: 302

In your views.py render statement, you should reference the template like this:


views.py for Posts App:

def index(request):
    # Notice that I am putting the template as "appname/template_file_name.html"
    return render(request, context={'..':...}, "posts/index.html") 

Another example

Your views.py for Users App

def login(request):
     return render(request, context, "users/login.html")

And it is as easy as that!

Upvotes: 1

Related Questions