Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django reverse using kwargs

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?

like image 549
EarlyCoder Avatar asked Oct 16 '15 15:10

EarlyCoder


2 Answers

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.

like image 32
YPCrumble Avatar answered Oct 15 '22 02:10

YPCrumble


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.

like image 174
Shang Wang Avatar answered Oct 15 '22 04:10

Shang Wang