简体   繁体   中英

Why does get_success_url keep directing me to the same page? (Django)

So I am new(ish) to Django, but have been working on a project for a few months. I decided to completely restructure the project to make it take more advantage of Django's Models. Basically what is happening here is I'm populating a form with a model-based view (CreateView) which gives the user a drop down selection of choices for which device they would like to interact with. However, whenever the form submits, it will always redirect me to the same page instead of 'success.html'

I have tried making the default template_name 'success.html' just to confirm that it can be displayed and also just tried returning 'success.html' without reverse, which still gives me the same page. Apologies in advance if I've left out something really small, I've been looking all over the place but haven't been lucky so far.

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>

From what I understand of your code, return reverse('success.html') always point to path('success/', DeviceChoiceView.as_view(), name='success.html') wich is your DeviceChoiceView. This would be why it's always rendering the same page uppon submit of the form. What you could do is change your success path to something like this.

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

For full doccumentation on TemplateView, you can check django's doc. https://docs.djangoproject.com/en/2.1/topics/class-based-views/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM