Django:'ImproperlyConfigured at' 在使用 CreateView 形成 POST 之后

Django: 'ImproperlyConfigured at' after form POST using CreateView

我想从表单(即 CreateView)向我的数据库添加数据。不幸的是,在发布后我得到了

'ImproperlyConfigured at/persons/new/'

我试图编辑我的 urls.py,但我想我错过了什么。

我的views.py

class PersonListView(ListView):
    model = Person
    template_name = 'app/home.html'
    context_object_name = 'users'

class PersonCreateView(CreateView):
    model = Person
    fields = ['name','surname']

我的urls.py在项目

*imports*
urlpatterns = [
    path('admin/',admin.site.urls),
    path('persons/', include('app.urls')),
]

我的 urls.py 在应用程序中

*imports*
urlpatterns = [
    path('',PersonListView.as_view(),name='persons),
    path('new/',PersonCreateView.as_view(),name='person-create),
]

提交表单后,数据已添加到数据库中,但出现如上所示的错误。

简答:您应该指定一个success_url [Django-doc] attribute in your view, or override form_valid [Django-doc]

CreateView [Django-doc] (well most views with a FormMixin [Django-doc]) 中,您需要指定成功处理表单后需要发生的事情。

默认一个ModelFormMixin [Django-doc] will first save the object [GitHub]:

def form_valid(self, form):
    """If the form is valid, save the associated model."""
    self.object = form.save()
    return <b>super().form_valid(form)</b>

然后基础 FormMixinredirect to the success_url [GitHub]:

def form_valid(self, form):
    """If the form is valid, redirect to the supplied URL."""
    return HttpResponseRedirect(<b>self.get_success_url()</b>)

get_success_url will retrieve the success_url attribute [GitHub],如您所见,如果缺少 ImproperlyConfigured 错误:

def get_success_url(self):
    """Return the URL to redirect to after processing a valid form."""
    if not self.success_url:
        raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.")
    return <b>str(self.success_url)</b>  # success_url may be lazy

在您看来,您可以指定一个 success_url,例如 reverse_lazy [Django-doc]:

from django.urls import <b>reverse_lazy</b>

class PersonCreateView(CreateView):
    model = Person
    fields = ['name','surname']
    <b>success_url = reverse_lazy('persons')</b>

这里persons是我们重定向到的path(..)名称。重定向通常是处理成功表单的首选方式:它是 Post/Redirect/Get architectural pattern [wiki] 的一部分。如果您要为 POST 请求呈现一个页面,那么在浏览器上刷新页面的用户将 重新发送 相同的数据到服务器,因此实际上可能会创建第二个对象。

另一种选择是覆盖 form_valid,并在 调用 super().form_valid(form) 之后 执行其他操作(因为那样会将对象保存到数据库)。