Django - Class Based Generic View - “No URL to redirect to”

无人久伴 提交于 2019-12-20 08:56:08

问题


I'm using the generic CreateView like:

#urls.py

from django.conf.urls.defaults import *
from django.views.generic import CreateView
from content.models import myModel

urlpatterns = patterns('myApp.views',
    (r'myCreate/$', CreateView.as_view(model=myModel)),
)

With a mymodel_form.html template like:

<form method="post" action="">
{% csrf_token %}
  {{ form.as_p }}
  <input type="submit" value="Submit" />
</form>

When I submit my form, the new object is created but I get the error

ImproperlyConfigured at ...

No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

How can I specify the url to redirect on success ?


回答1:


Have you tried passing in success_url? e.g.

CreateView.as_view(model=myModel, success_url="/success/")

or if you want to redirect to a named view:

CreateView.as_view(model=myModel, success_url=reverse('success-url'))



回答2:


you can also try to define get_absolute_url in your models. For example

class Something(models.Model):
    name = models.CharField(max_length=50, verbose_name='name')

    class Meta:
        pass

    def get_absolute_url(self):
        return u'/some_url/%d' % self.id 



回答3:


Add in views:

def form_valid(self, form):

   return self.render_to_response(self.get_context_data(form=form))



回答4:


views.py/

from django.views.generic import CreateView
from .models import myModel

class createView(CreateView):
    model = myModel
    fields = ['your fields', ...'']

    def get_success_url(self):
        return reverse('some_url')

urls.py/ (of your app)

from django.urls import path
from . import views

urlpatterns = [
    path('create/', views.createView.as_view(), name='create') 
] 


来源:https://stackoverflow.com/questions/6266415/django-class-based-generic-view-no-url-to-redirect-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!