J
J
Jomm2021-09-16 20:24:21
Django
Jomm, 2021-09-16 20:24:21

Why is request.user equal to AnonymousUser?

I implemented payment on the site using one payment system, which, if the payment is successful, redirects to the page using the POST method. I tried to change something in the db for a specific user, but nothing comes out

@csrf_exempt
def aaa(request):
  if request.method == 'POST':
    user = request.user
    user.username = request.POST['username']
    user.save()
  return render(request, 'main/aaa.html')

Sessions don't work either.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Kuts, 2021-09-24
@Jomm

If you look in your settings.MIDDLEWARE ,
you will see, for example , django.contrib.sessions.middleware.SessionMiddleware
which takes a session cookie from cookies and adds session data to the request:

session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME)
        request.session = self.SessionStore(session_key)

and then in the same place django.contrib.auth.middleware.AuthenticationMiddleware , in which, if you dig, you can find how the user is obtained from the session that we added to the request in the previous middleware. I'm just not going to list all the steps - otherwise it will be the topic of a separate long post.
Just walk around MIDDLEWARE and AUTHENTICATION_BACKENDS - see what comes from where. You can have some set of your own...
Therefore, if you don’t have a session cookie parameter in your cookie - stupidly in request.COOKIES there is no settings.SESSION_COOKIE_NAME parameter which is called sessionid by default - then the user has nowhere to take it from.
Therefore, dig more precisely what flies to you there. If there is no way to save a session cookie, then for example, you can add a hash to the redirect url, by which you can get the user by writing your own middleware if necessary...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question