I am trying to response the ajax when it successfully gets login but on the other hand, I want to check based on what user profile, it will redirect to the profile.
Following is my function in views.py
@csrf_exempt
def login_view(request):
next = request.GET.get('next')
email = request.POST.get("email")
password = request.POST.get("password")
user = authenticate(username=email, password=password)
if user is not None and user.is_active:
login(request,user)
if user.is_male:
return redirect('/male_profile')
elif user.is_female:
return redirect('/female_profile')
elif user.is_other:
return redirect('/other_profile')
data_json = {"error" : False, "errorMessage" : "Login Successful!"}
return JsonResponse(data_json, safe=False)
else:
data_json={"error":True,"errorMessage":"Username or password is incorrect!"}
return JsonResponse(data_json,safe=False)
What the problem I am facing is it only return Ajax response or redirect to user based profile.. but not both together. Can anyone please help me out with how can I first send the response to ajax and then I redirect it to another page in views.py based on user profile. Thanks.
CodePudding user response:
here you are returning JSON response so you cant redirect but this can be done as follow:
@csrf_exempt
def login_view(request):
next = request.GET.get('next')
email = request.POST.get("email")
password = request.POST.get("password")
user = authenticate(username=email, password=password)
if user is not None and user.is_active:
login(request,user)
if user.is_male:
redirect = 'male_profile'
elif user.is_female:
redirect = 'female_profile'
elif user.is_other:
redirect = 'other_profile'
data_json = {"error" : False, "errorMessage" : "Login Successful!",
"redirect": redirect}
return JsonResponse(data_json, safe=False)
else:
data_json={"error":True,"errorMessage":"Username or password is incorrect!"}
return JsonResponse(data_json,safe=False)
in HTML (on client side) on response, success check redirect key in response and make redirect in response success condition add
if (response.redirect){
location.href = response.redirect;
}