Django 使用 kwargs 进行反向操作

标签 django django-urls

比如说,在我的注册类的 post 方法中,如果用户已经注册,我想将用户重定向到登录页面,很简单。

class Register(View):
    ...
    def post(self, request):
        # Some code to check if the email address is already in the db
        message = {'message': 'You are already a member and registered the project.  Please just log-in',
                   'registration_date': the_registered_date}# The form with the filled-in data is returned
        return HttpResponseRedirect(reverse('accounts:login', kwargs = message))

在我的 urls.py 中:

#urls.py
...
url(r'^login/{0,1}$', Login.as_view(), name='login', kwargs={'message': None, 'date': None}),

这给了我错误消息:

Reverse for 'login' with arguments '()' and keyword arguments '{'message': 'You are already a member and registered the project.  Please just log-in', 'registration_date': datetime.datetime(2015, 10, 15, 14, 3, 39, 864000, tzinfo=<UTC>)}' not found. 2 pattern(s) tried: [u'accounts/$', u'accounts/login/{0,1}$']

我做错了什么?

最佳答案

你的url定义是错误的,听起来你也误解了什么kwargs位于reverse 。它为 url 定义的命名参数提供其值,而不是将上下文传递给 View 。

例如,您可以这样做:

url(r'test_suite/(?P<test_name>\w+)/(?P<test_id>\d+)$', 'test', name='test')
reverse('test', kwargs={'test_name': 'haha', 'test_id': 1})

kwargs将替换您的test_name在 url 定义中使用 hahatest_id1 。这将产生一个网址:test_suite/haha/1 .

关于Django 使用 kwargs 进行反向操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33173943/

相关文章:

python - 如果对象存在则从对象获取属性

python - 在 url 参数 DJANGO 中处理 '&'

mysql - 如何暂时禁用 MySQL 中的外键约束?

python - django 1.6.5 密码重置电子邮件检查有效链接

python - Heroku 使用 Django 应用程序筹集 500 而不是 404

python - urls.py 和重定向 url

python - 将值附加到序列化器数据

python - Django 1.8.3 网址

python - django静态文件相对路径不起作用

python - 要求django url中变量的最小长度