Home > Back-end >  The django rest framework is not able to recognize the User defined as foreign key
The django rest framework is not able to recognize the User defined as foreign key

Time:08-11

I'm trying to save a user profile information in a django model. The model is defined as follows

class UserProfile(models.Model): 
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  reg_date = models.DateTimeField(auto_now_add=True, blank=True)
  name = models.CharField(max_length=30, blank=True)
  family = models.CharField(max_length=30,  blank=True)
  phoneNumber = models.CharField(max_length=20,  blank=True)

  def __str__(self) :
    return self.name   self.family

The serializer for the model is defined as:

class UserProfileSerializer(serializers.ModelSerializer): 
  class Meta: 
    model= UserProfile
    fields = ['user', 'reg_date', 'name', 'family', 'phoneNumber']

and the view is as follows:

class UserProfileView(viewsets.ViewSet): 
  def create(self, request): 
    UserProfile.objects.create(user = request.user)

I'm sending a post request using axios as follows:

const a = await ProfileAPI.post('',
        {
          headers: {
            'Authorization': mytoken
          }
        })

in which mytoken is a logged in user token provided by dj-rest-auth API. Although the token is OK and the UserProfileView is executed by the request, I got the following error by the django rest:

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

Am I missed something? Is there any problem with my request or view? Please help me to fix this problem

CodePudding user response:

How authentication is determined

The authentication schemes are always defined as a list of classes. REST framework will attempt to authenticate with each class in the list, and will set request.user and request.auth using the return value of the first class that successfully authenticates.

If no class authenticates, request.user will be set to an instance of django.contrib.auth.models.AnonymousUser, and request.auth will be set to None.

The value of request.user and request.auth for unauthenticated requests can be modified using the UNAUTHENTICATED_USER and UNAUTHENTICATED_TOKEN settings.

Settings

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ]
}

Views

from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

class ExampleView(APIView):
    authentication_classes = [SessionAuthentication, BasicAuthentication]
    permission_classes = [IsAuthenticated]

    def get(self, request, format=None):
        content = {
            'user': str(request.user),  # `django.contrib.auth.User` instance.
            'auth': str(request.auth),  # None
        }
        return Response(content)

CodePudding user response:

Add in settings.py AUTH_USER_MODEL = '(app name).UserProfile'

  • Related