You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何渲染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.

Understanding Your View Logic

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. The request object holds all details about the user's incoming request (like browser info, headers, etc.).
  • posts = Post.published.all(): This line uses a custom manager named published (defined in your Post model, 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}): The render() shortcut does three key things:
    1. Looks for the HTML template at the path blog/post/list.html (we'll create this next)
    2. Passes the posts queryset (your list of published posts) to the template as a usable variable
    3. Renders the template with that data and sends the finished HTML back to the user's browser
Step-by-Step: Creating the HTML Template

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 the posts variable we passed from the view
  • {{ post.title }}: Outputs the title of each post (pulled directly from your Post model's title field)
  • {{ post.publish }}: Shows the post's publication date (from your model's publish field)
  • {{ post.body|truncatewords:30|linebreaks }}: Uses Django's template filters to:
    1. Truncate the post body to 30 words (so you don't show full posts on the list page)
    2. 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:

  1. Create a urls.py file in your blog app:
    # blog/urls.py
    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('', views.post_list, name='post_list'),
    ]
    
  2. Update your project's mysite/urls.py to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:44:10