Django,模型表格未在数据库中保存数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django,模型表格未在数据库中保存数据相关的知识,希望对你有一定的参考价值。
我是django的新手,我创建了一个表单来将数据保存到我的数据库中,但是它无法正常工作,我没有出现错误,但是数据未在数据库中发送。感谢您的帮助!
views.py
@login_required()
def data(request):
if request.POST == "POST":
form = CreatePost(request.POST)
if form.is_valid():
form.instance.author = request.user
form.save()
return redirect(data)
else:
form = CreatePost()
context = {
"form": form
}
return render(request, "sms/data.html", context)
forms.py
class CreatePost(forms.ModelForm):
class Meta:
model = Post
fields = ["title", "content"]
models.py
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
data.html
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<pre></pre>
<button class="btn btn-outline-info" type="submit" value="Submit">Data</button>
</form>
答案
尝试这样
@login_required()
def data(self, request):
if request.method == "POST": #this line
form = CreatePost(request.POST)
if form.is_valid():
post = form.save(commit=False) #new line
post.author = self.request.user #this line
post.save() #this line
return redirect(data)
else:
form = CreatePost()
context = {
"form": form
}
return render(request, "sms/data.html", context)
以上是关于Django,模型表格未在数据库中保存数据的主要内容,如果未能解决你的问题,请参考以下文章