在swagger页面上看不到django.views.generic中的formview视图API

xxls0lw8  于 2023-10-21  发布在  Go
关注(0)|答案(1)|浏览(115)

我正在使用Django和drf_yasg,我希望在使用表单视图时将此接口添加到swagger页面。然而,我试了几次,都没有成功。
代码如下:

class CustomRegisterView(FormView):
    template_name = "registration/register.html"
    form_class = RegisterForm
    success_url = reverse_lazy("home")
    swagger_schema = {
        "tags": ["user"],
        "method": "post",
        "operation_id": "register_user",
        "operation_description": "User registration with email and password",
        "request_body": openapi.Schema(
            type=openapi.TYPE_OBJECT,
            properties={
                "first_name": openapi.Schema(type=openapi.TYPE_STRING, default=""),
                "last_name": openapi.Schema(type=openapi.TYPE_STRING, default=""),
                "username": openapi.Schema(type=openapi.TYPE_STRING),
                "email": openapi.Schema(type=openapi.FORMAT_EMAIL),
                "password1": openapi.Schema(type=openapi.FORMAT_PASSWORD),
                "password2": openapi.Schema(type=openapi.FORMAT_PASSWORD),
            },
            required=["username", "email", "password1", "password2"],
        ),
        "responses": {
            status.HTTP_200_OK: openapi.Response(
                description="Successfully registered",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={"message": openapi.Schema(type=openapi.TYPE_STRING, description="Successfully registered")},
                )
            ),
            status.HTTP_400_BAD_REQUEST: openapi.Response(
                description="Registration failed",
                schema=openapi.Schema(
                    type=openapi.TYPE_OBJECT,
                    properties={
                        "detail": openapi.Schema(
                            type=openapi.TYPE_STRING,
                            description="Registration error message",
                        ),
                    },
                ),
            ),
        },
    }

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)

它不能帮助我调试在 Swagger 的网页,它不是呈现到 Swagger 的网页,主要原因是什么?我尝试了@swagger_auto_schema装饰器,它不工作。除了drf到标准的API编写方法之外,还有其他的视图编写方法吗?无法得到drf-yasg的支持?如果你想让FormView和django.contrib.auth.views中的视图呈现在swagger页面上,如何实现呢?

3z6pesqy

3z6pesqy1#

我在使用drf-spectacular时也遇到了同样的问题。我不确定斯瓦格的原因是否相同,但也许我的解决方案也适用于你。
原因是drf-spectacular丢弃了所有不是APIView类子类的视图,包括FormView。
我通过继承FormView和APIView解决了这个问题:

from rest_framework.views import APIView
from django.views.generic import FormView

class CustomRegisterView(FormView, APIView):
    ...

相关问题