Django Code Result not Displaying with include

Why is it that when I use an include for an example on my page, there is no result from Django Code showing ?

Django Code Result No Show

With screenshot above, you can see between
Loop through items of a list:
and In you can see what cars variable looks like.
that there is no result showing from Django code

As a for loops main page, I have a for_loops_tested.html file and it uses include for different examples to show on one page, like this:

<h4>For Loop List Dictionaries Example</h4>
{% include 'testing/for_loop_dict.html' %}

testing/for_loop_dict.html looks like this:

<p>Loop through items of a list:</p>

{% for x in cars %}
  <h1>{{ x.brand }}</h1>
  <p>{{ x.model }}</p>
  <p>{{ x.year }}</p>
{% endfor %} 

<p>In you can see what cars variable looks like.</p>

In my it has this code:

def for_loop_dict(request):
  template = loader.get_template('testing/for_loop_dict.html')
  context = {
    'cars': [
        'brand': 'Ford',
        'model': 'Mustang',
        'year': '1964',
        'brand': 'Ford',
        'model': 'Bronco',
        'year': '1970',
        'brand': 'Volvo',
        'model': 'P1800',
        'year': '1964',
  return HttpResponse(template.render(context, request))

and for this example, this is

 path('testing/for_loop_tested', views.for_loop_tested, name='for_loop_tested'),
 path('testing/for_loop_tested', views.for_loop_dict, name='for_loop_dict'),

My understanding is that you can use include tag and with for variables together, but how is it meant to be done with an example I have shown that uses an array ?

A requested url is matched to the first matching path. You’re never going to call views.for_loop_dict. The only view that will be executed is views.for_loop_tested. Please post that view.

Hi Ken

This is for_loop_tested view

def for_loop_tested(request):
    template = loader.get_template('testing/for_loop_tested.html')
    context = {
       'fruits': ['Apple', 'Banana', 'Cherry'],
    return HttpResponse(template.render(context, request))

This is used to display my page below
and the first example that shows Apple, Banana and Cherry

You see, what I am trying to do is have that showing and then use include for examples below first fruits example like the For List Dictionaries Example that explained was not showing currently.

Your for_loop_tested view doesn’t define a context variable named cars, so there’s nothing for the template to display.

How can I have both of these examples (fruits and cars) showing on same page ?

One thing I have noticed is that my for_loop_dict.html file is white in colour as can be seen below

Would I be better to have a view for whole page like this

def for_loop_tested(request):
  template = loader.get_template('testing/for_loop_tested.html')
  return HttpResponse(template.render())

and then have separate views for Loop through items of a list and Loop through a list of dictionaries examples.

Then the views don’t clash.

Focus on the fundamentals of the HTTP request/response cycle.

When the browser issues a request for a URL, what you get back is one page.

When Django receives that URL being requested, it is going to search through the defined URLs to find the first URL that matches the requested URL. It will then call that one view associated with that path.

That view will return one HttpResponse (or subclass thereof).

Everything that will be in that HttpResponse needs to be created by that view, including other functions it may call.

That means that that view needs to retrieve or create all data to be rendered on that page, and render all templates that are needed to produce that page.

How you do that is up to you.

You need to decide what the contents of a page are going to be, then create the view and template(s) to produce that page.

It is interesting to note that with another example on that same page , it displays a result from code I have used.
However I have noticed that it is using
'fruits': ['Apple', 'Banana', 'Cherry'], from first example that uses for_loop_tested view.

This indicates to me that there is a clash with views.

For Loop Last Example

In for loops main page for_loops_tested.html it uses include like this:

<h3 id="last">forloop.last</h4>

<p>Allows you to test if a loop is on its last iteration.</p>

<h4>For Loop Last Example</h4>

<p>Draw a blue background for last iteration of a loop:</p>

{% include 'testing/for_loop_last.html' %}

Here is include File for_loop_last.html

    {% for x in fruits %}
            {% if forloop.last %}
                style='background-color:lightblue; width:50px;'
            {% endif %}
        >{{ x }}</li>
    {% endfor %}        

<p>In you can see what fruits object looks like.</p>

Here is :

def for_loop_last(request):
    template = loader.get_template('testing/for_loop_last.html')
    context = {
        'fruits': ['Apple','Banana','Cherry', 'Oranges', 'Kiwi']
    return HttpResponse(template.render(context, request))

and in I have:
path('testing/for_loop_tested', views.for_loop_last, name='for_loop_last'),

That’s what I pointed out to you in my very first reply at Django Code Result not Displaying with include - #2 by KenWhitesell

As I was asking before, would I be better to have a view for whole page like this:

def for_loop_tested(request):
     template = loader.get_template('testing/for_loop_tested.html')
     return HttpResponse(template.render())

and then have separate views for each of the examples like I have shown on this post.

It should also be noted that I have a link in my template.html file to an example id on page like this

      <td><a href="/testing/for_loop_tested#last">forloop.last</a></td>
      <td>Allows you to test if the loop is on its last iteration.</td>

Links come from this testing page shown below:

and this is why I have more than one view with a path
path('testing/for_loop_tested', views.for_loop_last, name='for_loop_last'),

All examples are on the same page , but what separates them is an id in a heading for each example, as can be seen in this reply.

Can paths be done with id to different sections on a page ?

You ask me what you should do, but I don’t understand what your objective is for the page.

One view creates one page. One view does not call multiple views to create a page.

For any one page, your view needs to create or obtain all the data needed to be rendered on that page, and then render the templates.

I don’t think you quite see what I am wanting to achieve with this.

I have a page that has different sections.
I am talking about the for loop section that is in screenshot below

You see For Loops link goes to page.
Here is the key to understanding this, all links below the top one go to a specific part on page and this is done with an id.

Now I was mentioning that I thought I may have to change my view for the first For Loops link, so that it is like this

def for_loop_tested(request):
     template = loader.get_template('testing/for_loop_tested.html')
     return HttpResponse(template.render())

and have all examples as separate views and note separate html files that can be used with include in for_loop_tested.html.

I have seen that include and with can be used together in Django.

You know {% include 'testing/for_loop_last.html' %}
, but I believe you can also use with in include, I am just asking a question now, how can this be done with my examples like cars and fruits array ?

Surely Django should be able to do want I want to achieve ?

I appreciate your help so far, just want to move forward and get this working correctly, thanks.

What I think I’m understanding you to say:

You want to create a page, containing internal links to other parts of the same page.

However, you don’t want those other parts to be in the same template as your main page.

Is that correct? If so, then you can use include to include those different templates in your page. (And, I don’t understand where the “data” components come into this.)

(If I’m not correct, then I’m sorry, but it’s still not clear what you’re really trying to do here. It may be more helpful if you were more specific with your objective rather than trying to address this through an analogy. It may also be helpful if you just started with defining what all you want on this page, rather than trying to discuss how you think you want to create it.)

I thought I would mention now that I have actually had these pages setup already, but problem is that Django Code in my include file is not working for examples.
So this means that I am not getting anything displayed with examples, hopefully this makes sense.

Yes you are correct.

The main page that has all links to one page is this one.

and page these links go to is this page below.

As you can see on this page Django Examples are not displaying except result from


Hopefully this makes sense.

I just wonder if something in settings needs to be adjusted, so that Django Code can be recognised from an include file.

In my next reply I will show you some of my code I have pushed to GitHub, in particular include file.

Ok, I think I’m closer.

Again rephrashing to hopefully show understanding.

You have “View 1”. This view renders a template, “Template 1”.

“Template 1” includes “Template 2”. You want “Template 2” to contain data generated by “View 2”.

I think this is the gist of what you’re trying to achieve.

If so: No. It doesn’t work that way.

Templates don’t “call” views to be executed - the flow of control is only in the opposite direction. Views render templates.

If this is the situation you’re trying to achieve, then “View 1” needs to create or acquire all data needed to render “Template 1”, “Template 2”, etc.

You are calling one view to generate this page. You are not calling any other views.

On GitHub in my for_loop_tested.html file I have a First List Item Example
I have used include like this for this example {% include 'testing/for_loop_item.html' %}

and in for_loop_item.html file I have used this code below

{% for x in fruits %}
    <h1>{{ x }}</h1>
{% endfor %}

<p>In you can see what fruits variable looks like.</p>

But what I get displaying is just
In you can see what fruits variable looks like.

I think you can see from this example that problem is Django code is not displaying.

Another example Second List Dictionary Example
I have used include like this for this example {% include ‘testing/for_loop_dict.html’ %}

and in for_loop_dict.html file I have used this code below

<p>Loop through a list of dictionaries:</p>

{% for x in cars %}
  <h1>{{ x.brand }}</h1>
  <p>{{ x.model }}</p>
  <p>{{ x.year }}</p>
{% endfor %} 

<p>In you can see what cars variable looks like.</p>

But what I get displaying is

Loop through a list of dictionaries:

In you can see what fruits variable looks like.

This indicates to me that html code from my include file works, but not Django Code.
I am not sure how to fix this, but as I mentioned before could it be in my that this can be fixed.

It’s not the settings.

What you are trying to do here is fundamentally incorrect.

For your example here:

Your view that is rendering this page must provide the entry “cars” in your context.

No other view is involved here.

(You are also not showing “Django code” at all - that’s an incorrect phrasing of what’s happening here. You are rendering variables from a context.)

(Side note: If you’re trying to learn Django from W3Schools, don’t. Use better resources. Start with either or both of the Official Django Tutorial and the Django Girls Tutorial. Then find resources at GitHub - wsvincent/awesome-django: A curated list of awesome things related to Django)

Views for page
and 2 examples I have been talking about are in my file from lines 643 to 692
and I have

from django.http import HttpResponse
from django.template import loader

at top of on lines 44 to 47

I have a lot of comments, but you can ignore them as that is just to keep track of what is going on.

I have seen your last reply, it just seems like it isn’t that easy to get all these examples displaying correctly on one page.

How can this be done with Django ?

I have spent some time getting this done and I hope that I can get it completed in a way that works well.

It is. Just include all the code that generates the data in the one view.

Or, if you still want separate and independent pages to display these examples, refactor your code such that you have a function for each example. Call all the functions in your view that generates the “big” page, and each view that generates a single page calls the appropriate function.

Maybe you are right, there must be a nice efficient way like you are mentioning to do it.

I just wonder when all examples have different views how to deal with this.

You mention include all code that generates data in one view.
How does this work ?

W3Schools has Django for Tag on one page with examples for that topic and I think that this the best way to do it because you want examples all related to a topic.

We actually have two different situations here that I would handle in two different ways.

When you’re talking about a reference page - something that is showing you a static example and results, I would create this page with the actual html. I would not try to render data for each page retrieval. If I were building documentation for things like this, that is how I would do it. (It serves no purpose to go through the rendering process when that page is always going to show the same information.)

However, if you’re talking about a real project, where you’re showing live data, then you want to build your context from all the resources necessary for that page.

Something like this:

def my_view(request):
    context = {}
    context['fruit'] = [...]
    context['cars'] = { ... }
    return render(request, template, context)

Side note: If you’ve learned this
template = ...
pattern from this tutorial, it’s badly out of date. You really should be working from current / vetted material.