视图集:Tag对象的输入字段不显示,无法使用post方法创建Dot对象



不确定原因,但可能我以错误的方式向views.py中的上下文传递了请求,在views.py,其中post-method‘tag’输入字段缺少

class Dot(models.Model):
user = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE       
)
name = models.CharField(max_length=255)
description = models.TextField(max_length=350, blank=True)
lon = models.CharField(max_length=20)
lat = models.CharField(max_length=20)
rating = models.FloatField()
link = models.CharField(max_length=255, blank=True)
tag = models.ForeignKey('Tag', on_delete=models.PROTECT)
image = models.ImageField(null=True, upload_to=dot_image_file_path)

serializers.py

class TagSerializer(serializers.ModelSerializer):
class Meta:
model = Tag
fields = ('id', 'name')
read_only_fields = ('id',)

class DotSerializer(serializers.ModelSerializer):
tag = serializers.SerializerMethodField()
def get_tag(self, obj):
queryset = Tag.objects.filter(user=self.context['request'].user)
return TagSerializer(queryset, many=True).data

class Meta:
model = Dot
fields = ('id', 'name', 'description', 'lat', 'lon', 'rating', 'link', 'tag') 
read_only_fields = ('id',)

views.py-显示除"标记"之外的所有输入字段

class DotViewSet(viewsets.ModelViewSet):
serializer_class = serializers.DotSerializer
queryset = Dot.objects.all()
authentication_classes = (JWTAuthentication,)
permission_classes = (IsAuthenticated,)
def get_queryset(self):
queryset = self.queryset
return queryset.filter(user=self.request.user)
def get_serializer_context(self):
context = super().get_serializer_context()
context.update(request=self.request)
return context
class DotSerializer(serializers.ModelSerializer):
tag = TagSerializer()
def get_tag(self, obj):
queryset = Tag.objects.filter(user=self.context['request'].user)
return TagSerializer(queryset, many=True).data

class Meta:
model = Dot
fields = ('id', 'name', 'description', 'lat', 'lon', 'rating', 'link', 'tag') 
read_only_fields = ('id',)

相关内容

  • 没有找到相关文章

最新更新