0
votes

In my Django REST framework project i have this model:

class ml_request(models.Model):
    model_id = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now=True)
    p_country = models.CharField(max_length=100, blank=False, default='')
    p_description = models.TextField(null=False, blank=False)
    p_designation = models.CharField(max_length=200, blank=False, default='')
    p_points = models.IntegerField(default=00)
    p_price = models.IntegerField(default=00, blank=False)
    p_province = models.CharField(max_length=100, blank=False, default='')
    p_region_1 = models.CharField(max_length=100, blank=False, default='')
    p_region_2 = models.CharField(max_length=100, blank=False, default='')
    p_variety = models.CharField(max_length=100, blank=False, default='')
    p_winery = models.CharField(max_length=100, blank=False, default='')
    owner = models.ForeignKey('auth.User', related_name='req_owner', 
on_delete=models.CASCADE)
    highlighted = models.TextField()

class Meta:
    ordering = ('created',)

then i create my serializer like this:

from rest_framework import serializers
from botoapi.models import ml_request, ml_response, LANGUAGE_CHOICES, 
STYLE_CHOICES, ml_logs
from django.contrib.auth.models import User

class RequestSerializer(serializers.HyperlinkedModelSerializer):

    id = serializers.IntegerField(label='ID', read_only=True)
    highlight = serializers.HyperlinkedIdentityField(view_name='request-highlight', format='html')
    owner = serializers.ReadOnlyField(source='owner.username')

    class Meta:
        model = ml_request
        fields = ('id', 'model_id', 'highlight', 'created', 'p_country', 
'p_description', 'p_designation',
              'p_points', 'p_price', 'p_province', 'p_region_1', 'p_region_2', 
'p_variety', 'p_winery', 'owner')

        def create(self, validated_data):
            log_save = ml_logs(l_verbose=validated_data, l_method="CREATE", 
             l_action=validated_data.get("model_id", None))
            log_save.save()
            return validated_data

and is my view code:

class RequestViewSet(viewsets.ModelViewSet):
    queryset = ml_request.objects.all()
    serializer_class = RequestSerializer
    permission_classes = (IsAuthenticatedOrReadOnly,
                      IsOwnerOrReadOnly,)

    @detail_route(renderer_classes=[renderers.StaticHTMLRenderer])
    def highlight(self, request, *args, **kwargs):
        snippet = self.get_object()
        return Response(snippet.highlighted)

    def perform_create(self, serializer):
        serializer.save(owner=self.request.user)

bur when i run it and try to add values django return this error:

AttributeError at /requests/ 'dict' object has no attribute 'pk' Request Method: POST Request URL: http://127.0.0.1:8000/requests/ Django Version: 1.11.7 Exception Type: AttributeError Exception Value:
'dict' object has no attribute 'pk'

i have the id as PK and i add it in my serializer, someone can help me to wonder why this happens?

Thanks in advance

1
Show your views.pySébastien Deprez
Well i did it. thanksAleMal
I think your definition of id in the serializer is conflicting with the actual id field in the model.WombatPM

1 Answers

1
votes

From 3.x onwards,

If you want to add django auto 'id' explicitly in HyperlinkedModelSerializer, you need to use ReadOnlyField (not an IntegerField). Or else you can include it in 'fields'.

class RequestSerializer(serializers.HyperlinkedModelSerializer):
    id = serializers.ReadOnlyField()

And by default the serializer will include a url field instead of a primary key field. You can explicitly include the primary key by adding it to the fields option.

The name of the URL field defaults to 'url'. You can override this globally, by using the URL_FIELD_NAME setting.