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
JavaScript
x
20
20
1
def main(request):
2
form = CreateUserForm()
3
4
if "register-btn" in request.POST:
5
.
6
7
elif "login-btn" in request.POST:
8
username = request.POST.get('username-log')
9
password = request.POST.get('password-log')
10
user = authenticate(request, username=username, password=password)
11
if user is not None:
12
login(request, user)
13
return redirect('/account')
14
else:
15
messages.info(request, 'Username or password is incorrect')
16
#here I don't know what to write for the purpose of appearing the
17
#error messages on the page without refreshing it
18
19
return render(request, 'accounts/main.html', context)
20
Main.html ( briefly )
JavaScript
1
12
12
1
<label>Your login</label>
2
<input name="username-log" class="form-control" type="text" placeholder="Enter your login">
3
4
<label>Password</label>
5
<input name="password-log" class="form-control" type="password" placeholder="Enter your password">
6
7
{% for message in messages %}
8
<p id="messages" class="xerr"> {{message}} </p>
9
{% endfor %}
10
11
<button name="login-btn" class="btn btn_100" type="submit">LOG IN</button>
12
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