相关文章推荐
谈吐大方的筷子  ·  No converter for ...·  10 月前    · 
失望的斑马  ·  jquery ...·  1 年前    · 
健壮的芹菜  ·  Java生成XML文件 - ...·  1 年前    · 
热心肠的山羊  ·  C# 与vb.net ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm using djangorestframework together with drf-spectacular modules for a Django project, and I'm trying to build some basic API methods for my Project model. Its structure looks like this:

from django.db import models
# Create your models here.
class Project(models.Model):
    title = models.CharField(max_length = 128)
    description = models.TextField()
    image = models.URLField()
    date = models.DateTimeField(auto_now_add=True)

I also have a serializer for the model, looking like this:

from rest_framework import serializers
from api.models.Project import Project
class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = ['title', 'description', 'image', 'date']

Then, in views.py, I created two functions: project_list_view, which either lets you to GET all the Project objects from the database, or lets you POST a new object. And finally, project_detail_view, which lets you GET a Project object by typing in its pk (integer id). These are my two functions:

@api_view(['GET', 'POST'])
def project_list_view(request):
    if request.method == 'GET':
        projects = Project.objects.all()
        serializer = ProjectSerializer(projects, many=True)
        return Response(serializer.data)
    elif request.method == "POST":
        serializer = ProjectSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
def project_detail_view(request, pk):
    if request.method == "GET":
            project = Project.objects.get(pk = pk)
            serializer = ProjectSerializer(project, many = False)
            return Response(serializer.data, status = status.HTTP_200_OK)
        except:
            return Response(status=status.HTTP_404_NOT_FOUND)

The GET from project_list_view and project_detail_view work, but my problem lays in the POST method. My Swagger is set to display its API Schema when accessing http://127.0.0.1:8000/docs/, and as I said, GET methods work properly, but when I'm trying to click on "Try it out" at the POST method, the fields are not displayed. I can only press "Execute" without actually being able to complete anything. After I click on "Execute", Swagger returns a 404 Bad Request response.

This is how POST looks like in Swagger:

My question is: Why won't Swagger display fields for each parameter of the model? Thank you.

Swagger Grabs the fields from a serializer_class variable. I really recommend you change the format to Class-Based Views. Something using mixins or generic class.

Your view could be like

class ProjectView(mixins.RetrieveModelMixin, mixins.CreateModelMixin, viewsets.GenericViewSet):
    permission_classes = [permissions.IsAuthenticated, ] 
    serializer_class = ProjectSerializer
    queryset = Project.objects.all()
    def get(self, request, *args, **kwargs):
        return self.list(request, *args, **kwargs)
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

More on Mixins and Generic Views

Thank you for the clarification, but I want to learn how to use function based views first. I would like to firstly get used to the "low-level" stuff. Isn't it possible for me to use the same function based view, but edit the serializer in some certain way? – Mario Mateaș Nov 27, 2021 at 20:51 I appreciate your efforts to try to learn function based views. But I highly recommend migrate to Class Based Views, Works better with 3rd parties like swagger, and brings a lot to your project like reusability, implicit code, faster development, etc. I believe that's a way to manually describe the body of post request on swagger. unfortunately I don't know... – Carlos Carvalheira Nov 28, 2021 at 4:27 Thank you. Switched the POST method to a class-based view. Also marked your answer as a response! – Mario Mateaș Nov 28, 2021 at 9:04

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.