【问题标题】:SyntaxError: invalid syntax in URLpatternSyntaxError:URLpattern 中的语法无效
【发布时间】:2018-09-25 20:07:31
【问题描述】:

您好,遇到语法错误

网址:

url(r'^reset-password/$',
    PasswordResetView.as_view(template_name='accounts/reset_password.html', 'post_reset_redirect': 'accounts:password_reset_done'), name='reset_password'),

有什么问题?

谢谢

【问题讨论】:

  • 您在'post_reset_redirect': 'accounts:password_reset_done' 中使用了colon,而不是post_reset_redirect='accounts:password_reset_done'

标签: python django syntax


【解决方案1】:

问题是您将字典语法与参数语法混合在一起:

url(
    r'^reset-password/$',
    PasswordResetView.as_view(
        template_name='accounts/reset_password.html',
        'post_reset_redirect': 'accounts:password_reset_done'
    ),
    name='reset_password'
)

这种带有冒号的语法用于字典。参数为identifier=expression,所以:

from django.urls import reverse_lazy

url(
    r'^reset-password/$',
    PasswordResetView.as_view(
        template_name='accounts/reset_password.html',
        success_url=reverse_lazy('accounts:password_reset_done')
    ),
    name='reset_password'
)

post_reset_redirect 已作为参数删除,但 success_url 执行相同的功能:它是成功处理 POST 请求后重定向到的 URL。

错误的语法可能源于这样一个事实:当您使用基于函数的视图时,您通过接受字典的kwargs 参数传递参数。

然而,基于类的视图通过.as_view(..) 调用获取这些参数。此外,基于类的视图通常旨在概括该过程,其中success_url 用于FormViews。

【讨论】:

  • 感谢我现在收到此错误:TypeError:PasswordResetView() 收到无效的关键字“post_reset_redirect”。 as_view 只接受已经是类属性的参数。
  • 当我这样做时,我的 urlpattern 右括号出现语法错误 ]...我试过 )) 在 urlpattern 末尾,但后来我得到 'NameError: name 'reverse_lazy' is not defined跨度>
  • @JosephS:不,你需要导入它:from django.urls import reverse_lazy
  • 括号是 - afaik - 正确的(请注意,我们将它们都标上,一个在粗体的行,一个在下一行)。
猜你喜欢
  • 1970-01-01
  • 2021-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-31
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
相关资源
最近更新 更多