После использования login(request) для создания сессии в представлении login, сессия теряется при обращении к другому представлению в Django [duplicate]
Я пытаюсь создать модель клиент-сервер API в Django, но каждый раз, когда я вхожу в пользователя в моем представлении login. Когда мне нужно использовать информацию и сессию из логина, по какой-то причине она сбрасывается на AnonymousUser в моем представлении stories. А если я использую @login required, он просто перенаправляет меня на страницу входа, как будто я не авторизовался и не создал сессию с этим пользователем несколько минут назад. Вот мой views.py:
@csrf_exempt
def login_view(request):
if request.method == 'POST':
payload = request.POST
# Validate payload keys
if 'Username' not in payload or 'Password' not in payload:
return JsonResponse({'message': 'Username or password missing'}, status=400)
username = payload['Username']
password = payload['Password']
user = authenticate(request, username=username, password=password)
if user is not None:
# Log the user in and store session data
login(request, user)
return JsonResponse({'message': 'Login successful', 'user_id':user.id}, status=200)
else:
# Incorrect username or password
return JsonResponse({'message': 'Incorrect username or password'}, status=401)
@csrf_exempt
@login_required
def stories(request):
if request.method == 'POST':
if request.user.is_authenticated:
print(request.user.username)
# Retrieve data from the POST request
headline = request.POST.get('Headline')
category = request.POST.get('Category')
region = request.POST.get('Region')
details = request.POST.get('Details')
# Get the current user's author object
author = Author.objects.get(user=request.user.id)
author_name = author.name
# Create a new story object
new_story = Stories.objects.create(
headline=headline,
story_cat=category,
story_region=region,
autho_name=author,
story_date=timezone.now(),
story_details=details
)
return JsonResponse({'message': 'Story created successfully'}, status=201)
else:
return JsonResponse({'message': 'Authentication required'}, status=503)
else:
return JsonResponse({'message': 'Method not allowed'}, status=503)
и вот мой клиентский обработчик:
def login():
global login_status
url = 'http://127.0.0.1:8000/api/login/'
username = input("Enter username: ")
password = input("Enter password: ")
payload = {'Username': username, 'Password': password}
# Make sure to set 'Content-Type' header to 'application/x-www-form-urlencoded'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# Encode the payload as 'application/x-www-form-urlencoded'
data = '&'.join([f"{key}={value}" for key, value in payload.items()])
r = requests.post(url, data=data, headers=headers)
response_data = r.json()
if r.status_code == 200:
print("Login successful")
login_status = True
else:
print("Login failed:", response_data.get('message'))
def Post_story():
global login_status
url = 'http://127.0.0.1:8000/api/stories/'
headline = input("Enter a headline: ")
category = input("Enter a category(pol, art, tech, trivia): ")
region = input("Enter a region(uk, eu, w): ")
details = input("Enter story details: ")
payload = {'Headline': headline, 'Category': category, 'Region': region, 'Details': details}
# Make sure to set 'Content-Type' header to 'application/x-www-form-urlencoded'
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
# Encode the payload as 'application/x-www-form-urlencoded'
data = '&'.join([f"{key}={value}" for key, value in payload.items()])
r = requests.post(url, data=data, headers=headers)
response_data = r.json()
if r.status_code == 201:
print("Post successful")
else:
print("Post failed:", response_data.get('message'))
while True:
if login_status == False:
command = input("Enter command (login/exit): ").strip()
if command == "login":
login()
elif command == "exit":
break
else:
print("Invalid command. Please enter 'login', or 'exit'.")
if login_status == True:
command = input("Enter command (post/logout/exit): ").strip()
if command == "post":
Post_story()
elif command == "logout":
logout()
elif command == "exit":
break
else:
print("Invalid command. Please enter 'post', 'logout', or 'exit'.")
и при необходимости мой url.py:
from django.urls import path
from . import views
urlpatterns = [
# ex: /api/
path("", views.index, name="index"),
# ex: /api/login
path("login/", views.login_view, name="login"),
# ex: /api/logout
path("logout/", views.logout_view, name="logout"),
# ex: /api/stories
path("stories/", views.stories, name="stories"),
]
Я пробовал возиться с моим settings.py, пробовал вручную сохранять данные сессии с request.session, но по какой-то причине, как только представление меняется, сессия теряется. Я хочу избежать использования внешних библиотек для хранения сессий, но я пробовал очищать сессии и в консоли.