HadeS
HadeS

Reputation: 2038

Form validation error in django form without refreshing the page

I am stuck with the problem. I want to display any validation error found in the form like user doesn't exit, or wrong password etc. to be displayed on the login/signup form without page being reloaded.

I was able to submit the form but couldn't find a way to display error messages in the form.

Please help.

Upvotes: 1

Views: 2348

Answers (2)

Paulo Scardine
Paulo Scardine

Reputation: 77261

You must override the default login view and test for request.is_ajax. This is untested, any glitch is left as an exercise for you. Place a view like this at your login URL:

from django.contrib.auth.views import login as original_login
from django.conf import settings
from django.shortcuts import resolve_url
from django.contrib.auth import REDIRECT_FIELD_NAME, \
      login as auth_login
import json

def custom_login(request, template_name='registration/login.html',
          redirect_field_name=REDIRECT_FIELD_NAME,
          authentication_form=AuthenticationForm,
          current_app=None, extra_context=None):
    if request.method != 'POST' or not request.is_ajax():
        return original_login(request, template_name, 
            redirect_field, authentication_form, current_app,
            extra_context)

    form = AuthenticationForm(request.POST)
    if form.is_valid():
        auth_login(request, form.get_user())
        result = {
           "status": "OK",
           "url": resolve_url(settings.LOGIN_REDIRECT_URL)
        }
    else:
        result = {
            "status": "error",
            "errors": form.errors
        }

    return HttpResponse(json.dumps(result),
                        mime_type="application/json")

The trick is to return the original login view if the request is not a POST or is a POST but not AJAX, otherwise return a JSON object describing the result with the appropriate MIME type.

Upvotes: 1

shalakhin
shalakhin

Reputation: 4866

If you plan to have just few places with such interaction without page reloading you can avoid using Django Rest Framework and Ember/Angular/React etc.

  • on user input make ajax requst with javascript
  • on the server your view can recognise AJAX request with request.is_ajax() method and you can validate the form
  • in case everything is OK you can return status OK
  • in case there were errors you can return JSON object with field: "error message"

If you plan to have a lot of interactive functionality you should really consider using Angular/Ember/React and build an API with Django as was offered in comments to your question.

Upvotes: 2

Related Questions