【发布时间】:2019-02-28 16:11:10
【问题描述】:
所以我是 Django 的新手,但已经在一个项目上工作了几个月。我决定彻底重组这个项目,让它更多地利用 Django 的模型。基本上这里发生的事情是我正在使用基于模型的视图 (CreateView) 填充表单,该视图为用户提供了他们想要与之交互的设备的下拉选择选项。但是,无论何时提交表单,它都会将我重定向到同一页面而不是“success.html”
我尝试将默认模板名称设置为“success.html”,以确认它可以显示,并且还尝试不反向返回“success.html”,这仍然给了我相同的页面。如果我遗漏了一些非常小的东西,请提前道歉,我一直在寻找所有地方,但到目前为止还没有幸运。
views.py
class DeviceChoiceView(CreateView):
model = DeviceChoice
form_class = DeviceChoiceForm
success_url = 'success.html'
template_name = 'index.html'
def form_valid(self,form):
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('success.html')
urls.py
from django.contrib import admin
from django.urls import path
from django.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('port_reset/', include('port_reset.urls')),
]
port_reset/urls.py
from django.urls import path
from port_reset.views import DeviceChoiceView
from . import views
urlpatterns = [
path('', DeviceChoiceView.as_view(), name='index'),
path('success/', DeviceChoiceView.as_view(), name='success.html')
]
index.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>
【问题讨论】:
-
您有名为
success.html的视图还是只有模板? -
@GwynBleidD 只有一个模板。为它创建一个视图并以某种方式返回视图是最佳做法吗?