Reputation: 17
I'm working on a blog app and I'm trying to get all posts to be listed on the index/homepage.
Here's my BlogPost model:
from django.db import models
# Create your models here.
class BlogPost(models.Model):
title = models.CharField(max_length=200)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
return f"{self.text[:50]}..."
My views.py:
from django.shortcuts import render
from .models import BlogPost
# Create your views here.
def index(request):
posts = BlogPost.objects.order_by('-date_added')
body = BlogPost.objects.values('text')
context = {'posts': posts, 'body':body}
return render(request, 'blogs/index.html', context)
and my index.html:
<p> Blog </p>
<p> Here's some articles I've written: </p>
{% for post in posts %}
<h1> {{post}} </h1>
<p> {{body}} </p>
{%empty%}
<li> Sacrebleu! Where is me posts? </li>
{%endfor%}
The issue is how it's being displayed:
Blog
Here's some articles I've written:
Favorite things:
<QuerySet [{'text': "blah blah blah"}, {'text': "lorem ipsum"}]>
This is a test:
<QuerySet [{'text': "blah blah blah"}, {'text': "lorem ipsum"}]>
Instead, I'd like for it to display as:
Blog
Here's some articles I've written:
Favorite things:
blah blah blah
This is a test:
lorem ipsum
I feel like it has something to do with the id attribute, but I really can't point it out.
Upvotes: 1
Views: 711
Reputation: 48
You have to specify the parts of the post you want in the for loop, like this:
<p> Blog </p>
<p> Here's some articles I've written: </p>
{% for post in posts %}
<h1> {{post.title}} </h1>
<p> {{post.body}} </p>
{%endfor%}
Upvotes: 0
Reputation: 659
You can get the title and text for the blog post object in the html for loop.
views.py
def index(request):
posts = BlogPost.objects.order_by('-date_added')
context = {'posts': posts}
return render(request, 'blogs/index.html', context)
index.html
<p> Blog </p>
<p> Here's some articles I've written: </p>
{% for post in posts %}
<h1>{{ post.title }}</h1>
<p>{{ post.text }}</p>
{% else %}
<p> Sacrebleu! Where is me posts? </p>
{% endfor %}
Upvotes: 2