【问题标题】:Why I can not transfer "context" from endpoint Django app to HTML page?为什么我不能将“上下文”从端点 Django 应用程序传输到 HTML 页面?
【发布时间】:2023-03-09 10:38:02
【问题描述】:

我遇到了将 {context} 从 Django 端点传输到 HTML 的问题。我在项目中添加了第二个应用程序(第一个是“任务”,一切正常,第二个是“笔记”,问题出在这个)。我不知道为什么,但来自 context 的信息不会传输到 HTML。

Python:notes/views.py


@login_required(login_url='/user_login/')
def notes_list(request, *args, **kwargs):

if request.method == "POST":
    name = request.POST.get("name")
    description = request.POST.get("description")
    new_note = Notes.objects.create(
        name=name,
        description=description,
        user=request.user
        )
    new_note.save()
    return redirect("/notes_list/")

notes = Notes.objects.all().filter(user=request.user)
print("notes", notes)
context = {
    notes: "notes",
}
return render(request, 'notes_list.html', context)

HTML:模板/notes_list.html


List:
{%for note in notes%}
<b>Title:</b>
    <textarea  class="form-control" rows="1" cols="1"  name='name' >{{note.name}}</textarea>
<b>Note:</b>
    <textarea  class="form-control" rows="3" cols="1"  name='description' >{{note.description}}</textarea>
{%endfor%}

当我转到http://127.0.0.1:8000/notes_list/ 时,我只看到“列表:”和空白页面(没有备注列表)。模型 db 是正确的 - print("notes", notes) 在控制台中打印所有行,所以一切正常。

这是 settings.py 文件:


    TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
     },
   ]

【问题讨论】:

    标签: python html django render


    【解决方案1】:

    改变

    context = {
        notes: "notes",
    }
    

    context = {
        "notes": notes,
    }
    

    还在template{%%} 之前添加空格

    【讨论】:

      猜你喜欢
      • 2010-11-26
      • 1970-01-01
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 1970-01-01
      • 2021-05-06
      相关资源
      最近更新 更多