Django - Ajax registration

南笙酒味 提交于 2019-12-03 08:48:27

First you need to change the urls.py to wrap the existing view with another functionality. To do that you have to create a new backend package in backends folder and change urls.py there while keeping everything else intact, or you could just go ahead and modify the existing urls.py in the backend package.

I have not tested this, but it should work.

Point url to the new view:

# urls.py
url(r'^register/$', register_wrap,
    {'backend': 'registration.backends.default.DefaultBackend'},
    name='registration_register'),

# your new view that wraps the existing one
def register_wrap(request, *args, **kwargs):

    # call the standard view here
    response = register(request, *args, **kwargs)

    # check if response is a redirect
    if response.status_code == 302:
        # this was redirection, send json response instead
    else:
        # just return as it is
        return response

If you are going to need this for more views you can just create a decorator using this.

Why I would do is to check if request.is_ajax() in your normal after-successfull-registration-redirect view and return json response there.

You ask how you can use the existing view to manage the registration and send back a json response on success. Since the HttpResponseRedirect is pretty much hard coded in the view, you can't use the view as it is. Instead, either fork it, or write your own view and change the urls.py so that r'^register/$' directs to your new view.

As far as the json response is concerned, on success you can do something like this:

from django.utils import simplejson as json

def register_ajax(request):
    ...
    return HttpResponse(json.dumps(dict(success=True, **dict_containing_data)))

Hope this helps

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