Post List View
Now, let's create the post_list.html
file inside the template folder.
For now, the HTML file should be the following structure:
html9912345678910<!DOCTYPE html><html lang="en"><head><title>Title</title></head><body>{{ posts }}</body></html>
We implemented the post_list
view function:
python991234567891011def post_list(request):posts = Post.objects.all()html = ""for post in posts:html += f"<h1>{post.title}</h1>"html += f"<p>{post.text}</p>"html += f"<p>Post ID: {post.id}</p>"return HttpResponse(HTML)
Note
The presented code for the task is part of the framework and cannot work separately, so errors will be received when you try to
Run Code
. Use theSubmit Task
button to solve this task.
Taak
Swipe to start coding
-
Rewrite the
post_list
function using therender()
function. The render function should:- Receive the
request
as the first argument. - Receive the
post_list.html
template name as the second argument. - Receive the
context
dictionary as the third argument.
- Receive the
-
The
context
dictionary should contain the"post"
key with the iterable QuerySet of posts.
Oplossing
9
1
2
3
4
5
6
7
8
9
from django.shortcuts import render
from new_app.models import Post
def post_list(request):
context = {
"posts": Post.objects.all()
}
return render(request, "post_list.html", context)
Was alles duidelijk?
Bedankt voor je feedback!
Sectie 5. Hoofdstuk 3
single
99
1
2
3
4
5
6
7
8
9
10
from django.shortcuts import render
from new_app.models import Post
def post_list(request):
___ = {
"___": Post.objects.___()
}
return ___(___, "___", ___)
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.