【问题标题】:Why does get_success_url keep directing me to the same page? (Django)为什么 get_success_url 一直将我引导到同一页面? (姜戈)
【发布时间】: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 只有一个模板。为它创建一个视图并以某种方式返回视图是最佳做法吗?

标签: python django


【解决方案1】:

根据我对您的代码的理解,return reverse('success.html') 始终指向path('success/', DeviceChoiceView.as_view(), name='success.html'),这就是您的 DeviceChoiceView。这就是为什么它总是在提交表单时呈现相同的页面。你能做的就是把你的成功之路改成这样。

path('success/', TemplateView.as_view(template_name="success.html"))

有关 TemplateView 的完整文档,您可以查看 django 的文档。 https://docs.djangoproject.com/en/2.1/topics/class-based-views/

【讨论】:

  • 谢谢@Zykerd。这现在让我显示成功页面。 :)
  • 我的荣幸 :) 祝项目重组顺利。
猜你喜欢
  • 1970-01-01
  • 2011-12-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-10
  • 2017-10-15
  • 2016-07-14
  • 2012-04-26
  • 1970-01-01
相关资源
最近更新 更多