我创建了一个具有几个字段的模型表单,并希望在用户向模板中输入值并单击提交时保存数据。
但是,当我单击“提交”时,值不会从表单中清除,并且数据也不会保存到我使用select * from notes_note;
我没有收到任何错误,只是没有保存该数据。
Models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Note(models.Model):
owner = models.ForeignKey(User, on_delete=models.DO_NOTHING,)
title = models.CharField(max_length=100)
text = models.CharField(max_length=500)
createTime = models.DateTimeField()
from django.forms import ModelForm
class NoteForm(ModelForm):
class Meta:
model = Note
#fields = '__all__'
#fields = ['title', 'text', 'createTime']
exclude = ['owner']
模板
<a href="/notes/logout/">Log Out</a>
<h2>Dashboard {{ user }}</h2>
<table>
<tr>
<td>
<form_name="noteForm" action="/notes/dashboard/" method="post"> {% csrf_token %}
{{ form.as_p }}
<input type= "submit" value="New Note"/>
</form>
</td>
</tr>
</table>
Views.py
@login_required(login_url="/notes/index/")
def dashboard(request):
if request.method == 'POST':
# d dict is a copy of our request.Post because it's immutable and we need to add owner
d = request.POST.copy()
d.update({'owner': request.user.id})
form = NoteForm(d)
if not form.is_valid():
template = loader.get_template('dashboard.html')
context = {
'form': form,
}
return HttpResponse(template.render(context, request=request))
# save the note to the database
# if the form is valid
note = form.save()
note.owner = request.user
note.save()
return redirect("dashboard")
else:
print("this prints out")
template = loader.get_template('dashboard.html')
context = {
'form': NoteForm(),
}
return HttpResponse(template.render(context, request=request))
我在views.py的仪表板功能中使用了一条打印语句,以查看正在处理的内容,并且该内容正在其他部分。