Django model owner field reading the log in user as None instead of the username

santhosh

I am trying to learn django rest framework and have been following the django-rest-framework tutorial. I am not able to understand why my model's owner field is taking None value instead of logged in user as it is a foreign key.

Please find my code below

my model

class Wish(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length=100,blank=True,default='')
    wishtext = models.TextField()
    owner = models.ForeignKey('auth.User', related_name='wishes', on_delete=models.CASCADE, null=True)

    class Meta:
       ordering = ('created',)

If I don't use null=True its generating NOT NULL constraint error

my views

class WishList(generics.ListCreateAPIView):

    queryset = Wish.objects.all()
    serializer_class = WishSerializer
    permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly)
    # print("object reached here  , permissions.IsAuthenticatedOrReadOnly")

class WishDetail(generics.RetrieveUpdateDestroyAPIView):

    queryset = Wish.objects.all()
    serializer_class = WishSerializer
    permission_classes = (IsOwnerOrReadOnly, permissions.IsAuthenticatedOrReadOnly)

my serliazers

class WishSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = Wish
        fields = '__all__'


class UserSerializer(serializers.ModelSerializer):
    wishes = serializers.PrimaryKeyRelatedField(queryset=Wish.objects.all(), many=True)

    class Meta:
        model = User
        fields = ['id', 'username', 'wishes']

my object level permission

class IsOwnerOrReadOnly(permissions.BasePermission):

    def has_object_permission(self, request, view, obj):
        # Read permissions are allowed to any request,
        if request.method in permissions.SAFE_METHODS:
            return True

        # Write permissions are only allowed to the owner of the wish.
        return obj.owner == request.user

print(obj.owner) is showing None in the output and NULL in database, I couldn't understand the issue.

Abdul Aziz Barkat

You have used serializers.ReadOnlyField for your owner field. This means that it will not be used when creating instances and will only be shown in serialized responses. Looking at your code you have then used this same serializer for your view inheriting from ListCreateAPIView which is the view I assume you use for creating objects. Hence it is no mystery that your field owner ends up being None.

Instead if you want to use the current logged in user as the one that made the object you can use SlugRelatedField [DRF docs] to show the username, set it to be read_only and use pass it's default as CurrentUserDefault [DRF docs]:

class WishSerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(
        # In case only the actual creator will be owner
        default=serializers.CreateOnlyDefault(serializers.CurrentUserDefault()),
        # In case editor can become owner
        # default=serializers.CurrentUserDefault(),
        read_only=True,
        slug_field='username'
    )

    class Meta:
        model = Wish
        fields = '__all__'

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Django 2.2 and Rest Framework 3.11 - partial updating model "owner" field (ForeignKey) with owner's username string instead of pk

Multiple USERNAME_FIELD in django user model

Compare Django model field and request.user.username in HTML

How do I add username of logged in user to model field in django

How to save Username instead of Object name(None) automatically while saving the model in django

Django custom User model throwing SystemCheckError - The field 'username' clashes with the name 'username'

How to change the field of username to user_name in to django custom user model?

User Follower model in Django. To show username instead of email of the people users follow

Django get user by generic USERNAME_FIELD

Django model Field default=None useful?

Django saving in a model with User field

Login user for a custom user model with email as username field

Django model field set default user in model

How to associate a username from the User model to another model in Django?

authenticate(request, username=username, password =pswd) returns None for custom user model

Field name user_username is not valid for model Profile

Django-REST: Get User by username instead of primary-key

How to register a user with Email instead of username in Django Rest Framework

Log in user using either email address or username in Django

Accessing a field on a Django model that is linked to a different model via the User model

Omitting password field for custom django user model

Django admin model field set to current user

Django: Customize the User model's return field

Add a field to the Django admin for a custom user model

Adding data to a Django model associated with a user field

DJANGO,DRF:request id returning a NONE value instead the user object

Putting username of logged in user as label in django form field

Remove/hiding username field in django admin edit user form

Django Rest Framework: Serialize User ManyToMany field by username