Rendering Django View Data to HTML

Viewed 45

I am creating a learning portal, in which students can learn on various books. Each book will have various chapters / topics.

Each topic is having a unique slug, as reflected the below mentioned model, which we want to render / show on an HTML page, upon clicking on it.

I want to show the contents of the topic on a separate HTML page, when somebody click on that particular topic. I have written the below mentioned code, however, failed to populate the data on the HTML.

My Django model, view.py and url.py is as under.

My Django model is as follows:

class book_explination(models.Model):
       title = models.CharField  (max_length = 255)
       slug = models.SlugField(max_length= 250, null = True, blank = True, unique= True)
       lesson_no = models.CharField  (max_length = 255)
       book_text = models.TextField  (blank=False, null=False)

my view is as follows:

def topic_detail(request, url):
    topic_detail = book_explination.objects.get(slug = url)
    return render(request, 'blog/topic_detail.html', {'topic_detail':topic_detail})

the url.py is as under:

path('', books_list, name = "books_list"),
    path('book_topics/', book_topics, name = "book_topics"),
    path('book_topics/<slug:url>/', topic_detail, name = 'topic_detail'),

The HTML rendering page is as follows:

{% block content %}
  <div class="container">
    <p> {{lesson_no | safe}} </p>
    <p> {{book_text | safe}} </p>
    <p> {{book_text_explination | safe}} </p>
  </div>
{% endblock %}    


<ul>
  {% for c in topic_detail %}
    <li>{{ c.lesson_no }}</li>
    <li>{{ c.lesson_no }}</li>
    <li>{{ c.lesson_no }}</li>
  {% endfor %}
</ul>

I would be very thankful for your help. Thanks

1 Answers

You need to add your loop inside block tag

{% block content %}

      <div class="container">
        <p> {{lesson_no | safe}} </p>
        <p> {{book_text | safe}} </p>
        <p> {{book_text_explination | safe}} </p>
      </div>
    
    <ul>
      {% for c in topic_detail %}
        <li>{{ c.lesson_no }}</li>
        <li>{{ c.lesson_no }}</li>
        <li>{{ c.lesson_no }}</li>
      {% endfor %}
    </ul>
{% endblock %}    

Addition: I recommend you to use get_object_or_404

from django.shortcuts import get_object_or_404

def topic_detail(request, url):
    topic_detail = get_object_or_404(book_explination, slug=url)  
    return render(request, 'blog/topic_detail.html', {'topic_detail':topic_detail})
Related