无法在我的 html 模板中获取对象
Unable to get the object in my html template
我已经在我的应用程序的管理页面中创建了对象,但我无法在我的 html 模板中调用该对象。我会将视图和 html 行放在下面
from django.shortcuts import render, redirect
from .models import *
from .forms import *
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'tasks': tasks, 'form': form}
return render(request, 'todo_app/list.html')
{% for task in tasks %}
<div class="task-container">
<p>{{task}}</p>
</div>
{% endfor %}
您忘记将 context 发送到模板:
Optional arguments
context
A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.
context = {'tasks': tasks, 'form': form}
return render(request, 'todo_app/list.html', context)
我已经在我的应用程序的管理页面中创建了对象,但我无法在我的 html 模板中调用该对象。我会将视图和 html 行放在下面
from django.shortcuts import render, redirect
from .models import *
from .forms import *
def index(request):
tasks = Task.objects.all()
form = TaskForm()
if request.method == 'POST':
form = TaskForm(request.POST)
if form.is_valid():
form.save()
return redirect('/')
context = {'tasks': tasks, 'form': form}
return render(request, 'todo_app/list.html')
{% for task in tasks %}
<div class="task-container">
<p>{{task}}</p>
</div>
{% endfor %}
您忘记将 context 发送到模板:
Optional arguments
context
A dictionary of values to add to the template context. By default, this is an empty dictionary. If a value in the dictionary is callable, the view will call it just before rendering the template.
context = {'tasks': tasks, 'form': form}
return render(request, 'todo_app/list.html', context)