Kosmylo
Kosmylo

Reputation: 428

request.user always returns AnonymousUser

I have created a django model which includes a foreign key to a user as follows:

from authentication.models import User
from django.db import models

class Event(models.Model):
    
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    dr_notice_period = models.IntegerField(blank=True, null=True)
    dr_duration = models.IntegerField(blank=True, null=True)
    dr_request = models.FloatField(blank=True, null=True)

My serializers.py file is as follows:

class EventSerializer(serializers.ModelSerializer):

    user = UserSerializer(many=True, read_only=True)

    class Meta:
        model = Event
        fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request']

My views.py is as follows:

from rest_framework.response import Response
from rest_framework.decorators import api_view
from rest_framework import status

from vpp_optimization.serializers import EventSerializer

@api_view(['POST'])
def event(request):

    serializer = EventSerializer(data=request.data)

    if serializer.is_valid():
        instance = serializer.save(commit=False)
        instance.user = request.user
        instance.save()
        return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
    else:
        return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

What I need to do is to go to a URL and login as a user. Then I need to go to another URL and add with POST request some details about the event and save the details as well as the user in the database. However after login and POST request I get the following error:

Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f7daf1469d0>": "Event.user" must be a "User" instance.

It seems that it always returns an AnonymousUser, although I have logged in. Any idea of how can I solve this issue?

The settings.py are the following:

REST_FRAMEWORK = {
    'DEFAULT_FILTER_BACKENDS': [
        'django_filters.rest_framework.DjangoFilterBackend'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
}

Upvotes: 2

Views: 2175

Answers (1)

Ranu Vijay
Ranu Vijay

Reputation: 1249

you will have to provide

permission_classes = [IsAuthenticated]  # DjangoModelPermissionsWithRead

in your views.

Edits.

everytime you access your views for any type of request you should pass token such as.

axios
  .get(
    `http://localhost:8000/anything`,
    {
      headers: {
        Authorization: `Token ${token}`,
      },
    }
  )

edit 2 -

you are wrong importing your user, use this -

from django.contrib.auth import get_user_model
User = get_user_model()

Upvotes: 0

Related Questions