Micromegas
Micromegas

Reputation: 1689

How to render a template in django from a different app using Class Based Views?

I'm feeling I shouldn’t be asking thins question because it seems too easy. But I can't find a solution in the django docs or here.

I want to render a template in my class based generic ListView, which is in the templates folder of a different app.

My folder structure:

my_website
   -app1
   -app2
   -mywebsite
      -templates
         -users
            -welcome_pages
               -welcome_user.html

   -app3
     -templates
        -mytemplate.html
        -mytemplate2.html
     -views.py
     -models.py

In my app3 I have a view that looks like this:

class VisualizationView(StaffRequiredMixin, ListView):
    template_name = ????
    model = Project

    def get_context_data(self, **kwargs):
        print(self.get_template_names())
        context = super(VisualizationView, self).get_context_data(**kwargs)
        context['projects'] = Project.objects.all()

        return context

So I can easily render a template now in template_name which is in my app3 and spit out all my project objects there. But I want to render the context in welcome_user.html.

Normally the documentation says I should use appname/templatename but I get a TemplateDoesntExist Exception. I tried passing to template_name:

mywebsite/welcome_user.html
mywebsite/users/welcome_pages/welcome_user.html
welcome_user.html
mywebsite/templates/users/welcome_pages/welcome_user.html

If I print out self.get_template_names() I only get a list of templates that are within app3. I thought django would automatically be looking in the whole project wherever a template folder is? What am I missing here? Or is this not supposed to work in a CBV?

Apologies if this is a too easy question and thanks for any help. Appreciated !

Upvotes: 2

Views: 1402

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476719

The fact that the template is located in a different app does not make any difference. The template folders are searched. So it means you can acces the template with:

class VisualizationView(StaffRequiredMixin, ListView):
    template_name = 'users/welcome_pages/welcome_user.html'
    model = Project

    def get_context_data(self, **kwargs):
        print(self.get_template_names())
        context = super(VisualizationView, self).get_context_data(**kwargs)
        context['projects'] = Project.objects.all()

        return context

If you have set the APP_DIRS setting [Django-doc] to True, it will thus search the template directories of the apps, and eventually find a users/ directory in the template/ directory of your users/ app, and find the relevant template.

Upvotes: 2

Related Questions