Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unable to access object's property despite it being present

My serializer:

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = "__all__"

    def create(self, validated_data):
        try:
            print(validated_data)
            print(validated_data.author)
            task = Task.objects.create(**validated_data)
            return task
        except BaseException as e:
            print(e)
            raise HTTP_400_BAD_REQUEST

my view:

class TaskCreateApiView(generics.CreateAPIView):
    serializer_class = TaskSerializer

my model:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

from django.db import models
from django.contrib.auth.models import User

class Task(models.Model):
    content = models.CharField(
        default="",
        max_length=255,
    )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        null=True,
    )
    category = models.CharField(
        default="",
        max_length=255,
    )

    def __str__(self):
        return str(self.id) + self.content

My log from serializer:

{‘content’: ‘test2’, ‘category’: ‘test’, ‘author’: <User: zaq1>}

‘dict’ object has no attribute ‘author’
print(validated_data.author)
^^^^^^^^^^^^^^^^^^^^^
AttributeError: ‘dict’ object has no attribute ‘author’

How can I access author? I see it exists as <User:zaq1> but can’t seem to access it

>Solution :

The error is because you print validate_data.author, whereas it should be validate_data['author']:

class TaskSerializer(serializers.ModelSerializer):
    class Meta:
        model = Task
        fields = '__all__'

    def create(self, validated_data):
        try:
            print(validated_data)
            print(validated_data['author'])
            task = Task.objects.create(**validated_data)
            return task
        except BaseException as e:
            print(e)
            raise HTTP_400_BAD_REQUEST

That being said, normally manually creating in a serializer is a (serious) antipattern: a lot of work in the serializer goes to creating objects with many-to-many fields, or deeply nested data.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading