0

Django newbie question - I need to display a specific entry in a template. So far I have not been able to get this to work. I have the following code:

model:

class BasicPage(models.Model):
    title = models.CharField(max_length=200)
    body = HTMLField()

    def __str__(self):
        return self.title

view:

class TermsPageView(TemplateView):
    model = BasicPage
    template_name = 'terms.html'

    def get_queryset(self):
        body = BasicPage.objects.filter(id=1)
        return body

template:

{% block content %} 

<h1>{{ body.title }}</h1>

{% endblock content %}

2 Answers 2

1

We would need more information to solve this issue, but I guess that, as get_queryset returns a QuerySet which is an iterable, to display body in you template you need to use a for loop :

{% block content %} 
{% for i in body %}
<h1>{{ i.title }}</h1>
{% endfor %}
{% endblock content %}

Anyway, using TemplateView to return a single item filter(id=1) seems to indicate that you need to deep digger in documentation, this kind of view aims to be generic, not return a single item with unique ID.

Sign up to request clarification or add additional context in comments.

Comments

0

To pass this object as a context, you need to use get_context_data:

class TermsPageView(TemplateView):
    model = BasicPage
    template_name = 'terms.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['body'] = BasicPage.objects.get(id=1)
        return context

Note that this is using get so you will only get one object. But if you really want to use a queryset (if you use filter), then you need to iterate through the list as @May.D has indicated.

1 Comment

This probably makes the most sense since I only want to return one object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.