无法获取我的 html 模板中的对象

发布于 2025-01-16 18:48:14 字数 732 浏览 2 评论 0原文

我已在应用程序的管理页面中创建了对象,但无法在 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 %} 

I've created objects in the admin page of my app, but I'm unable to call the object in my html template. I will put the views and the html lines below

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 %} 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

四叶草在未来唯美盛开 2025-01-23 18:48:14

您忘记将上下文发送到模板:

可选参数

上下文

要添加到模板上下文的值字典。默认情况下,这是一个空字典。如果字典中的值是可调用的,视图将在渲染模板之前调用它。

    context = {'tasks': tasks, 'form': form}
    return render(request, 'todo_app/list.html', context)

You forgot to send context to template:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文