Ear*_*der 3 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))
Run Code Online (Sandbox Code Playgroud)
在我的urls.py中:
#urls.py
...
url(r'^login/{0,1}$', Login.as_view(), name='login', kwargs={'message': None, 'date': None}),
Run Code Online (Sandbox Code Playgroud)
这给了我错误信息:
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}$']
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
您的网址定义是错误的,也听起来像你误解了kwargs的呢reverse.它使用它的值提供url定义的命名参数,而不是将上下文传递给视图.
例如,您可以这样做:
url(r'test_suite/(?P<test_name>\w+)/(?P<test_id>\d+)$', 'test', name='test')
reverse('test', kwargs={'test_name': 'haha', 'test_id': 1})
Run Code Online (Sandbox Code Playgroud)
kwargs将取代您test_name在网址定义haha和test_id使用1.这将产生一个网址:test_suite/haha/1.
Kwargs inreverse是进入您的 URL 的变量,以使其唯一。在 URL 中看到消息/日期真的很奇怪……这就是你的 URLconf 正在尝试做的事情。
另外,你无法在 Django 中使用上下文进行重定向,而不会遇到麻烦,这使得果汁不值得挤压。如果您想在重定向后执行此操作,一种选择是使用消息框架在登录页面上显示消息。
我的解决方案是从 /login/ 的 URLConf 中删除 kwargs ,并使用消息框架(或会话)在重定向后将信息传递到登录页面。
| 归档时间: |
|
| 查看次数: |
1352 次 |
| 最近记录: |