Ahti Ahti - 4 years ago 66
jQuery Question

How to redirect user and display his/her username to a different page in Ajax?

I am trying to redirect the user (who has successfully logged in) to an article page with his/her username. but for some reason i don't see the username of the user in the article page.

article html:

<div class="container post" >
<h2 class="author"><a>{{ username }}</a></h2>
<hr>
<h6 class="subject"> </h6>
<p class="comment"><br><br>
</div>


article view:

def article(request):
template = 'librarysystem/article.html'
return render(request, template)


Ajax:

$('#loginForm').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/librarysystem/Login/",
data: {
'username':$("#loginUsername").val(),
'password':$("#loginPassword").val(),
csrfmiddlewaretoken:$
('input[name=csrfmiddlewaretoken]').val
()
},
dataType: 'json',
success: function(data){
if (data.response){
initalizeForm();
$("#invalid").html(" ");
$('#loginmodal').modal('hide');
console.log(data.username);
window.location = data.redirectTo + "?username=" + data.username;
}else
$("#invalid").html("<h5> Invalid username or password. </h5>").css('color','red');
},
error: function(jqXHR, status, err){
alert(jqXHR.responseText);
}
});
});


urls.py:

from django.conf.urls import url
from .import views

urlpatterns = [
url(r'^register/$',views.registerUser),
url(r'^$', views.index, name="Index"),
url(r'^validateRegisterForm/$',views.validateRegisterForm),
url(r'^validateLoginForm/$',views.validateLoginForm),
url(r'^article/$', views.article, name="Article"),
url(r'^Login/$',views.loginUser, name="Login"),
url(r'^Logout/$',views.logoutUser, name="Logout"),
]


views.py:

def loginUser(request):
data = {}
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username,password=password);
if user is None:
data['response'] = False
else:
login(request,user)
data['response'] = True
data['redirectTo'] = "/librarysystem/article/"
data['username'] = username
return JsonResponse(data)

Answer Source

As it is an Ajax response and you are passing the string as a query string to the url you won't be able to use the username directly in the template. You can either get the variable of query string with {{request.get.username}}. or As the user is logged in we can access the user object directly in the view when you render your template with render(request, '<template_name>') in your template you can access username as following

{{user.username}} or {{request.user.username}}

It is better to user {% if user.is_athenticated %} condition before using {{user.username}} that checks if the user is logged in or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download