[Django]-Django, custom authentication login. How to display error message when authentication fails?

6👍

You should first create a Registration Form in forms.py, like this:

class RegistrationForm(forms.Form):
    email = forms.EmailField(label='Email')
    password = forms.CharField(label='Password', widget=forms.PasswordInput())

You should then import and pass this form to your template, so add this to your view:

# import the RegistrationForm (change AppName to the name of you app)
from AppName.forms import RegistrationForm

def login_user(request):
  form = RegistrationForm() # add this
  logout(request)
  email = password = ''

  if request.POST:
    form = RegistrationForm(request.POST) # and add this

   ## rest of the code goes here ##

    context = RequestContext(request, {
        'state': state,
        'email': email,
        'form': form, # pass form to the front-end / template
    })

    return render_to_response('customauth/login.html', {}, context)

and make this your login.html:

{% if form.errors %}
    {{ form.errors }} <!-- display the form errors if they exist -->
{% endif %}

<!-- display the form -->
<form action="/login" method="post">
    {% csrf_token %}
        {{ form }} <-- this displays all the form fields -->
    <input type="submit" value="Submit" />
</form>

Leave a comment