【问题标题】:Django: redirect to DetailView without pk in URLDjango:在 URL 中没有 pk 的情况下重定向到 DetailView
【发布时间】:2018-05-18 13:42:20
【问题描述】:

我想用 Django1.11 制作注册表单。

urls.py

app_name = 'accounts'

urlpatterns = [
    url(r'^create/$', views.SignUpView.as_view(), name='create'),
    url(r'^check/$', views.CheckView.as_view(), name='check'),
    url(r'^update/$', views.CorrectView.as_view(), name='update'),
    # ...
]

views.py

class SignUpView(CreateView):
    model = User
    form_class = UserForm
    template_name = "accounts/create.html"

    def get_success_url(self):
        check_view = CheckView.as_view()
        return redirect(check_view, pk=self.object.pk)

class CheckView(DetailView):
    model = User
    template_name = "accounts/check.html"

class CorrectView(UpdateView):
    model = User
    form_class = UserForm
    template_name = "accounts/create.html"

    def get_success_url(self):
        check_view = CheckView.as_view()
        return redirect(check_view, pk=self.object.pk)

新用户在 SignUpView(generic.CreateView) 中输入信息后,他会在 CheckView(generic.DetailView) 中看到他刚刚输入的内容,如果他发现自己犯了一些错误,他会在 CorrectView(generic) 中重新输入他的信息.UpdateView)。

例如,我不想创建 url r'^check/(?P<pk>[0-9]+)$'。这是因为如果用户在浏览器中输入一个 URL .../check/1,很不幸他可以看到另一个人的信息。

当我运行上面的代码时,出现了错误Reverse for 'accounts.views.CheckView' not found. 'accounts.views.CheckView' is not a valid view function or pattern name. 。请告诉我如何在没有 url 的情况下重定向到 CheckView(generic.DetailView) 包含 pk。

【问题讨论】:

  • 你这里用的是认证,所以只能显示认证用户的信息?

标签: python django redirect django-class-based-views


【解决方案1】:

您可以将 url 的结构更改为不使用 slug,例如:

# Url dell'app accounts.
url(r'^accounts/register/$', RegistrationView.as_view(form_class=CustomUserForm), name='registration-register'),
url(r'^accounts/profile/$', UserProfileView.as_view(), name='user-profile'),
url(
    r'^accounts/profile/(?P<company>[-\w]+)/modifica/$',
    UpdateCompanyView.as_view(),
    name='update-company-view-profile'
),
url(
    r'^accounts/change-password/$',
    password_change, {'post_change_redirect': 'user-profile'}, name='password_change'
),
url(r'^accounts/update/$', UserProfileUpdateView.as_view(), name='user-profile-update'),
url(r'^accounts/', include('registration.backends.hmac.urls')),

这是我在项目中使用的 url 的结构.. 然后我就可以操纵用户,或者简单地使用 request.user 从中获取信息!

【讨论】:

  • 谢谢!这个解决方案很有帮助!我佩服你!
  • @Zuya 很高兴为您提供帮助 :)
猜你喜欢
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2020-06-22
  • 2014-07-12
  • 2011-09-28
  • 2018-01-18
  • 2020-05-07
  • 1970-01-01
相关资源
最近更新 更多