首页 > 解决方案 > 为什么添加 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>

标签: pythondjango

解决方案


您正在覆盖通常在 form_valid() 中实现的 save() 函数,因此它阻止了表单提交到数据库。

model = form.save(commit=False)
model.save()

在返回重定向之前添加它。


推荐阅读