如何渲染HTML模板?对Django视图渲染模板逻辑的困惑
Let's break this down clearly—first I'll explain what your existing view does, then walk you through building the HTML template step by step to render those posts.
First, let's unpack that post_list view you have:
def post_list(request):: This is a Django view function, acting as the middleman between your database and the user's browser. Therequestobject holds all details about the user's incoming request (like browser info, headers, etc.).posts = Post.published.all(): This line uses a custom manager namedpublished(defined in yourPostmodel, per the book) to fetch all posts marked as "published" from your database—this filters out drafts or unpublished content.return render(request,'blog/post/list.html',{'posts': posts}): Therender()shortcut does three key things:- Looks for the HTML template at the path
blog/post/list.html(we'll create this next) - Passes the
postsqueryset (your list of published posts) to the template as a usable variable - Renders the template with that data and sends the finished HTML back to the user's browser
- Looks for the HTML template at the path
Right now, your blog app doesn't have a templates directory—let's fix that and build the template.
1. Build the Template Directory Structure
Django expects templates to live in a templates folder inside your app, and nesting them under blog/post/ avoids conflicts with other apps. Create these folders in your blog directory:
~/mysite/blog/templates/blog/post/
Your updated blog directory will look like this:
~/mysite/blog/ ├── admin.py ├── apps.py ├── __init__.py ├── migrations/ ├── models.py ├── __pycache__/ ├── templates/ │ └── blog/ │ └── post/ │ └── list.html # This is the file we'll create ├── tests.py └── views.py
2. Write the list.html Template
Open the new list.html file and add this basic template code (you can style it later with CSS):
<!-- blog/templates/blog/post/list.html --> <h1>My Blog</h1> {% for post in posts %} <div class="post"> <h2>{{ post.title }}</h2> <p class="publish-date">Published on: {{ post.publish }}</p> <p>{{ post.body|truncatewords:30|linebreaks }}</p> </div> {% empty %} <p>No published posts yet.</p> {% endfor %}
Let's explain the template syntax here:
{% for post in posts %}: Loops through every post in thepostsvariable we passed from the view{{ post.title }}: Outputs the title of each post (pulled directly from yourPostmodel'stitlefield){{ post.publish }}: Shows the post's publication date (from your model'spublishfield){{ post.body|truncatewords:30|linebreaks }}: Uses Django's template filters to:- Truncate the post body to 30 words (so you don't show full posts on the list page)
- Convert line breaks in the body to proper HTML
<br>/<p>tags
{% empty %}: Shows this message if there are no published posts to display
3. Make Sure Django Can Find Your Template
Double-check that your blog app is added to INSTALLED_APPS in mysite/settings.py—Django automatically looks for templates in apps listed here:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', # This line must exist! ]
4. Wire Up the URL (So You Can View It)
To access this view in your browser, you need to map it to a URL:
- Create a
urls.pyfile in yourblogapp:# blog/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.post_list, name='post_list'), ] - Update your project's
mysite/urls.pyto include the blog URLs:# mysite/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('blog/', include('blog.urls')), # Add this line ]
5. Test It Out
Start your Django development server:
python manage.py runserver
Then visit http://127.0.0.1:8000/blog/ in your browser—you should see your list of published posts (or the "No published posts yet" message if you haven't added any).
内容的提问来源于stack exchange,提问作者MikiBelavista

