Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Post List View | Templates
Django: First Dive

book
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:

html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Title</title>
</head>
<body>
{{ posts }}
</body>
</html>

We implemented the post_list view function:

python
def 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 the Submit Task button to solve this task.

Aufgabe

Swipe to start coding

  1. Rewrite the post_list function using the render() 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.
  2. The context dictionary should contain the "post" key with the iterable QuerySet of posts.

Lösung

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)

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 5. Kapitel 3
from django.shortcuts import render
from new_app.models import Post


def post_list(request):
___ = {
"___": Post.objects.___()
}
return ___(___, "___", ___)

Fragen Sie AI

expand
ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

We use cookies to make your experience better!
some-alt