Django reverse using kwargs

偶尔善良 提交于 2021-01-27 16:44:52

问题


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))

in my urls.py:

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

This gives me the error message:

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

What am I doing wrong?


回答1:


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 will substitute your test_name in url definition with haha and test_id with 1. This will produce a url: test_suite/haha/1.




回答2:


Kwargs in reverse are the variables that go into your URL to make it unique. It would be really odd to see a message/date inside a URL...which is what your URLconf is trying to do.

Also, you can't redirect with context in Django without going to trouble that makes the juice not worth the squeeze. One option is to use the messages framework to display a message on the login page if you want to do that after the redirect.

My solution would be to remove the kwargs from your URLConf for /login/ and use the messages framework (or sessions) to pass the information to the login page after the redirect.



来源:https://stackoverflow.com/questions/33173943/django-reverse-using-kwargs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!