Django使用kwargs反向 [英] Django reverse using kwargs

查看:35
本文介绍了Django使用kwargs反向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say, in the post method of my registration class, I want to redirect the user to the login page if the user is already registered, simple enough.

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中:

in my 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}$']

我在做什么错了?

推荐答案

您的网址定义有误,听起来也像是您误解了 kwargs reverse 中所做的事情.它将URL定义的值作为URL定义的命名参数,而不是将上下文传递给视图.

Your url definition is wrong, also sounds like your misunderstood what kwargs does in reverse. It feeds the named arguments of your url definition with it's value, not passing context to the view.

例如,您可以执行以下操作:

For example, you could do this:

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 会将url定义中的 test_name 替换为 haha​​ ,将 test_id 替换为 1 .这将产生一个网址: test_suite/haha​​/1 .

kwargs will substitute your test_name in url definition with haha and test_id with 1. This will produce a url: test_suite/haha/1.

这篇关于Django使用kwargs反向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆