python - 为什么添加 Django 重定向会阻止数据库填充?
问题描述
所以,长话短说,我在实现 Django CreateViews 时遇到了问题。我非常接近让它发挥作用,但突然出现了一个新问题。如果没有以下代码中的重定向,我的数据库将填充新的模型实例。但是,将重定向添加到成功页面后,我无法在我的数据库或 Django 管理页面中看到新的模型实例。如果我遗漏了一些简单的东西,请提前道歉。如有必要,我可以发布更多代码,但我的猜测是它会出现在 views.py 或我的模板中
视图.py
class SuccessView(TemplateView):
template_name = "success.html"
class DeviceChoiceView(CreateView):
model = DeviceChoice
form_class = DeviceChoiceForm
success_url = 'success.html'
template_name = 'index.html'
## All the code below this point is what stops the database from populating ##
def form_valid(self,form):
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return ('success')
索引.html
<!DOCTYPE html>
<html>
<head>
<title>Port Reset</title>
</head>
<body>
<h1>Device Database</h1>
<form action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" id="deviceSelection" value="Submit">
</form>
</body>
解决方案
您正在覆盖通常在 form_valid() 中实现的 save() 函数,因此它阻止了表单提交到数据库。
model = form.save(commit=False)
model.save()
在返回重定向之前添加它。
推荐阅读
- mysql - 计算mysql中的连续行
- django - 在 Django 中为除用户以外的模型创建身份验证系统
- graphql - 如何使用 Amplify 为 GraphQL API (AWS AppSync) 生成类
- php - 如何使用codeigniter 4框架在mysql数据库中插入多行?
- android - 如何将 `android` Kotlin DSL 添加到 buildSrc 模块中的类路径?
- windows - 有没有办法在 Kivy 中绘制一个平滑的 RoundedRectangle?
- python - 当所有内容都是数字python时替换值
- java - 当我们从另一个 char 整数中减去一个 char 整数时会发生什么?
- apache-spark - Pyspark:在窗口中拼接多个事件行
- javascript - 如何在 RxJs (BehaviourSubject) 中使用 TypeScript 进行严格的类型检查?