I am looking for a solution to the following problem:
I have a main function which contains many kind of QuerySets and python codes. In this function there are many query which has to be run only when user authenticated. I know that when I use @login_required
before the function I can authenticate the user but how can I use the authentication inside the function?
My example code:
def auth(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return render(request, 'project/index.html')
else:
login(request, user)
def dashboard_data(request):
qs1 = MyModel.objects.all()
qs2 = MyModel.objects.all()
qs3 = MyModel.objects.all()
#Lets say I want to run the the following queries when user logged in
qs_logged1 = MyModel.objects.all()
qs_logged2 = MyModel.objects.all()
send_data = {
'qs1': qs1,
'qs2': qs2,
'qs3': qs3,
'qs_logged1':qs_logged1,
'qs_logged2':qs_logged2
}
return render(request, 'project/index.html', send_data)
How could I run the queries abobe only when user logged?
def dashboard_data(request):
qs1 = MyModel.objects.all()
qs2 = MyModel.objects.all()
qs3 = MyModel.objects.all()
if request.user.is_authenticated:
qs_logged1 = MyModel.objects.all()
qs_logged2 = MyModel.objects.all()
send_data = {
'qs1': qs1,
'qs2': qs2,
'qs3': qs3,
'qs_logged1': qs_logged1,
'qs_logged2': qs_logged2
}
return render(request, 'project/index.html', send_data)
else:
send_data = {
'qs1': qs1,
'qs2': qs2,
'qs3': qs3,
}
return render(request, 'project/index.html', send_data)