[英]save() method does not save form data to the database (Django ModelForm)
I'm making a simple todo list using Django, it works fine except that whatever data is entered into the form does not save to the database (and does not get displayed).我正在使用 Django 制作一个简单的待办事项列表,它工作正常,除了输入到表单中的任何数据都不会保存到数据库中(并且不会显示)。
My models.py:我的模型.py:
from django.db import models
class TodoListItem(models.Model):
content = models.TextField()
def __str__(self):
return self.content
forms.py: forms.py:
from .models import TodoListItem
from django.forms import ModelForm
class TodoListForm(forms.ModelForm):
class Meta:
model = TodoListItem
fields = ['content']
views.py:视图.py:
from django import forms
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from .models import TodoListItem
from .forms import TodoListForm
def home(request):
context = {
'items': TodoListItem.objects.all()
}
return render(request, 'home.html', context)
def enter_task(request):
if request.method == 'POST':
form = TodoListForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/')
else:
return HttpResponse('Form not valid')
else:
form = TodoListForm()
return render(request, 'form.html', {'form': form})
I did it according to the documentation, what I fail to understand is why the line form.save()
won't execute when return HttpResponseRedirect('/')
right underneath it does.我是根据文档做的,我不明白为什么行
form.save()
在return HttpResponseRedirect('/')
就在它下面时不会执行。
The form.html file, just in case: form.html 文件,以防万一:
<!DOCTYPE html>
<html>
<head>
<title>Add task</title>
<h1>Add Task</h1>
</head>
<body>
<form action="{% url 'home' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</body>
</html>
I know that the error has to be in views.py because I used the admin site to add to TodoListItem manually and the html file does display it perfectly fine, just that whenever I submit the form it never saves to the aforementioned model.我知道错误必须在views.py中,因为我使用管理站点手动添加到TodoListItem,并且html文件确实显示得很好,只是每当我提交表单时它永远不会保存到上述model。
It is happening that you have entered the form action incorrectly发生您错误地输入了表单操作
<form action="{% url 'home' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
you have to put this url inside your form action enter_task
您必须将此 url 放入表单操作
enter_task
<form action="{% url 'enter_task' %}" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
It looks like your form action is sending the form to your homepage rather than the URL that points to the enter_task view.看起来您的表单操作正在将表单发送到您的主页,而不是指向 enter_task 视图的 URL。 I don't know this for sure without seeing your urls.py but that's what I'd check.
如果没有看到您的 urls.py,我不确定这一点,但这就是我要检查的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.