when I use firefox or edge,after I use user=authenticate(request,username=username,password=password)
login(request,user)
,
and then I reload my front-end page, the request.user is still anonymous,but when I use chrome, it login successfully,what’s wrong?
I don’t really know exactly what happened but you can check these hypotheses:
-
Clear your browsers cache or just navigate with private window.
-
insert the
@login_required
decorator on the view -
you can also verifie if the request.user.is_anonymous returns True.
thank you,I insert the @login_required and the front-end page console said ```www.ytysite.ltd/:1
Access to XMLHttpRequest at 'https://ytysite.ltd/accounts/login/?next=/settings/login/%3Fusername%3Dadmin%26password%3DyangT521.' (redirected from 'https://ytysite.ltd/settings/login?username=admin&password=yangT521.') from origin 'https://www.ytysite.ltd' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. ``` on edge,and the chrome still login successfully
you obviously using Django Rest Framework ?
So you need to include the CORS management systems in your settings file.
It allow your front to be able to communicate with the back.
You need these:
python -m pip install django-cors-headers
In your installed app, insert this
-
'corsheaders',
)
In your MIDDLEWARE, insert this
-
'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware',
]``
After find somewhere at bottom to insert this
CORS_ALLOWED_ORIGINS = [*]
this is the link for further informations Cors
thank you so much! but my console error changes to www.ytysite.ltd/:1
Access to XMLHttpRequest at 'https://ytysite.ltd/settings/getinfo/?platform=web' from origin 'https://www.ytysite.ltd' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://www.ytysite.ltd, https://www.ytysite.ltd', but only one is allowed.
Try to put ‘*’ which means “all” in CORS_ALLOWED_ORIGINS = ['*']
and add CORS_ORIGIN_ALLOW_ALL = True
Don’t forget the link in my third point
Is it related to my nginx? there is a add_header 'Access-Control-Allow-Origin' '*'
in my nginx.conf
I don’t think so, try to have access without the NGINX server to see the behavior .
I delete the add_header in my nginx.conf and the console error changed to
GET https://ytysite.ltd/accounts/login/?next=/settings/login/%3Fusername%3Dyty%26password%3DyangT521. 404 (Not Found)
now when I login