2

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?

2 Answers2

2
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)
Exprator
  • 26,992
  • 6
  • 47
  • 59
  • Why having two distinct definitions of send_data and two distinct calls to render ??? – bruno desthuilliers Mar 27 '18 at 06:58
  • Your answer helped me a lot, I didn't use two times the `send_data`, after the `else` I defined empty variables (e.g `qs_logged1=[]`), and after that the function have ran correctly. –  Mar 27 '18 at 08:34
2

You can use is_authenticated for check whether the user is logged-in or not

def dashboard_data(request):
    if request.user.is_authenticated:
        # do something with authenticated user
    else:
        # do something without authenticated user
    return something

You can also refer to this SO post for the same

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JPG
  • 82,442
  • 19
  • 127
  • 206