Search code examples
djangodjango-viewsdjango-registration

Django - Ajax registration


I am trying to allow registration (using this django-registration register view) to one of my applications from a modal dialog.

Since this form is in a modal box, I'd like to get an json reponse on success (instead of the default redirection)

How can I use this view (django-registration register) to manage the registration and send back a json response on success ?


I know how to make ajax/json responses, the question is how to use the django-registration view without the redirection behavior or wrap it into an other view to manage the response.


Solution

  • 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.