Django模板数据展示求助:模板未渲染,如何从视图传数据至模板?
Hey there! Let's fix that template rendering issue you're facing. Passing data from views to templates is a fundamental part of Django's MVT architecture, so I'll walk you through the process clearly with examples.
Step 1: Prepare and Pass Data in Your View
In your views.py, you need to package the data you want to display into a context dictionary, then pass it to the template using Django's render() function (or TemplateResponse for more control).
Example View Code:
from django.shortcuts import render def your_view_name(request): # 1. Define the data you want to send to the template page_title = "Welcome to My Django App" featured_posts = [ {"title": "First Post", "content": "Hello World!"}, {"title": "Second Post", "content": "Django is awesome!"} ] user_is_authenticated = request.user.is_authenticated # 2. Create a context dictionary with your data context = { "page_title": page_title, "posts": featured_posts, "is_logged_in": user_is_authenticated } # 3. Pass the context to the template when rendering return render(request, "your_template.html", context)
If you're using Class-Based Views (like TemplateView), override the get_context_data() method to add your custom data:
from django.views.generic import TemplateView class YourClassView(TemplateView): template_name = "your_template.html" def get_context_data(self, **kwargs): # Get the default context from the parent class context = super().get_context_data(**kwargs) # Add your custom data context["greeting"] = "Hello from a Class-Based View!" return context
Step 2: Render the Data in Your Template
Now in your template file, use Django's template syntax to access the context variables. Use {{ variable_name }} for single values, and template tags like {% for %} or {% if %} for logic.
Example Template Code:
<!DOCTYPE html> <html> <head> <title>{{ page_title }}</title> </head> <body> <h1>{{ page_title }}</h1> {% if is_logged_in %} <p>Welcome back, {{ request.user.username }}!</p> {% else %} <p>Please log in to see more content.</p> {% endif %} <h2>Featured Posts:</h2> <div class="posts"> {% for post in posts %} <div class="post"> <h3>{{ post.title }}</h3> <p>{{ post.content }}</p> </div> {% empty %} <p>No posts available right now.</p> {% endfor %} </div> </body> </html>
Common Pitfalls to Avoid
- Double-check template paths: Make sure your template is in the correct
templatesdirectory (either app-specific or project root), and the path inrender()matches exactly. For example, if your template is inmyapp/templates/myapp/your_template.html, use"myapp/your_template.html"as the path. - Case sensitivity: Context keys and template variables are case-sensitive—
{{ Page_Title }}won't work if your context uses"page_title". - Ensure the view is mapped to a URL: Don't forget to add a URL pattern in
urls.pythat points to your view, otherwise the template won't be loaded at all.
内容的提问来源于stack exchange,提问作者pawas kr. singh

