Django Rest Framework with Images

0

Well I'm still studying this framework, I researched a little tried some ways but they did not work.

Error:

  

'UnboundLocalError at / api / services / 1 / local variable' Service '   referenced before assignment '

Code:

Serializer

from .models import Servico
from rest_framework import serializers

class ServicoSerializer(serializers.ModelSerializer):

    imagem = serializers.ImageField(max_length=None, use_url=True)

    class Meta:
        model = Servico
        depth = 1
        fields = '__all__'

Model

from django.db import models

def upload_location(instance, filename):
    return "%s/%s" %(instance.id, filename)

class Servico(models.Model):
    nome = models.CharField(max_length = 120, verbose_name='Servico')
    valor = models.DecimalField(decimal_places=2, max_digits=20)
    descricao = models.TextField(verbose_name='descricao', null=True)
    jornada = models.CharField(max_length = 120, verbose_name='jornada')
    imagem = models.ImageField(upload_to=upload_location ,null=True,blank=True,
        width_field="width_field",
        height_field="height_field")
    height_field = models.IntegerField(default=0)
    width_field = models.IntegerField(default=0)

View

class ServicoView(APIView):
     serializer_class = ServicoSerializer

     def get(self, request, pk, format=None):
         Servico = Servico.objects.get(pk=pk)
         serializer = self.serializer_class(Servico)
         return Response(serializer.data)

    def put(self, request, pk, format=None):
        Servico = Servico.objects.get(pk=pk)
        serializer = self.serializer_class(Servico, data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def delete(self, request, pk, format=None):
        Servico = Servico.objects.get(pk=pk)
        Servico.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
    
asked by anonymous 26.07.2018 / 05:24

1 answer

1

From what I see in the code that you put of view.py , you're using the Servico model but at the same time creating a variable with the same name Servico .

    
28.07.2018 / 18:54