姜戈;无法在主页上显示管理页面的备注



我正在创建我的第一个 Django 笔记应用程序,我正在尝试在主页上插入和显示笔记。不幸的是,我只设法如何在数据库中插入它们,但我无法在主页上显示它们。

这是我 views.py 文件:

from django.shortcuts import render, render_to_response
from django.template import RequestContext, loader
from django.http import HttpResponse
from .models import Note
from .forms import NoteForm
def home(request):
notes = Note.objects
template = loader.get_template('note.html')
form = NoteForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
context = {'notes': notes, 'form': form}
return render(request, 'note.html', context)

这是我的 html 文件:

<link href="http://codepen.io/edbond88/pen/CcgvA.css" media="screen" rel="stylesheet" type="text/css">
<style>
body {<br />
background: rgba(222,222,222,1);<br />
margin: 20px;<br />
}<br />
</style>
<h1>Notes App</h1>

<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<td>&nbsp;</td>
<input type="submit" value="Add note">
</form>

我正在尝试从本教程制作应用程序:https://pythonspot.com/django-tutorial-building-a-note-taking-app/

你需要Note.objects.all()而不是views.pyNote.objects

def home(request):
notes = Note.objects.all()
template = loader.get_template('note.html')
form = NoteForm(request.POST or None)
if form.is_valid():
save_it = form.save(commit=False)
save_it.save()
context = {'notes': notes, 'form': form}
return render(request, 'note.html', context)

此外,您需要迭代它们以在模板中显示它们:

<h1>Notes App</h1>
{% for note in notes %}
<p>{{ note }}</p>
{% endfor %}

试试这个:

return render(request, 'note.html', context=context)

取而代之的是:

return render(request, 'note.html', context)

而这个:

notes = Note.objects.all()

取而代之的是:

notes = Note.objects

我看到的第一个问题是你没有在表单中添加任何操作。action属性应该是要将表单提交到的视图。

所以这是你应该首先做的:

<h1>Notes App</h1>
<form method="POST" action="whatever_your_url_for_this_page_is">
{% csrf_token %}
{{ form.as_p }}
<td>&nbsp;</td>
<input type="submit" value="Add note">
</form>

最新更新