Skip to content
Advertisement

If the username or password is invalid when logging in, how can appear an error on page without refreshing itself, Django

I have a login pop-up and I want after typing wrong username or password to appear a error message, like usual ‘Username or password is incorrect’, but after pressing button on the site, it is refreshing and I need to open my pop-up again in order to see the error, how can I do the error msg to appear without refreshing the page.

Views.py

def main(request):
    form = CreateUserForm()

    if "register-btn" in request.POST:
        ....

    elif "login-btn" in request.POST:
        username = request.POST.get('username-log')
        password = request.POST.get('password-log')
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect('/account')
        else:
            messages.info(request, 'Username or password is incorrect')
            #here I don't know what to write for the purpose of appearing the 
            #error messages on the page without refreshing it

    return render(request, 'accounts/main.html', context)

Main.html ( briefly )

<label>Your login</label>
<input name="username-log" class="form-control" type="text" placeholder="Enter your login">

<label>Password</label>
<input name="password-log" class="form-control" type="password" placeholder="Enter your password">

   {% for message in messages %}
      <p id="messages" class="xerr"> {{message}} </p>
   {% endfor %}

<button name="login-btn" class="btn btn_100" type="submit">LOG IN</button>

Advertisement

Answer

I can see that OP has the concern to inform the users about what’s going on and decided to use the messages framework for that – that’s great. Now the question that pops up is “How can one do that without the page refreshing?”.

As nigel239 mentions, one’ll have to go with asynchronous JavaScript. There are various Q&As articles that explain how to submit the forms asynchronously, such as

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement