【问题标题】:how django browsableapi generate html form automatically?django browsableapi如何自动生成html表单?
【发布时间】:2019-02-05 08:13:00
【问题描述】:

我正在学习 DRF,但我对 DRF 序列化程序如何在 browsableapi 中生成 HTML 表单感到困惑。我有 UserRegistrationAPIView 和 UserRegistrationSerializer。

class UserRegistrationAPIView(CreateAPIView):
    authentication_classes = ()
    permission_classes = ()
    serializer_class = UserRegistrationSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)

        user = serializer.instance
        token, created = Token.objects.get_or_create(user=user)
        data = serializer.data
        data["token"] = token.key

        headers = self.get_success_headers(serializer.data)
        return Response(data, status=status.HTTP_201_CREATED, headers=headers)

class UserRegistrationSerializer(serializers.ModelSerializer):
    # password = serializers.CharField(write_only=True, style={'input_type': 'password'})
    confirm_password = serializers.CharField(write_only=True, style={'input_type': 'password'})
    confirm_password1 = serializers.CharField(write_only=True, style={'input_type': 'password'})

    class Meta:
        model = User
        fields = ("id", "username", "email", "password", "confirm_password", "date_joined","confirm_password1")

    def create(self, validated_data):
        del validated_data["confirm_password"]
        del validated_data["confirm_password1"]
        return super(UserRegistrationSerializer, self).create(validated_data)

    def validate(self, attrs):
        if attrs.get('password') != attrs.get('confirm_password'):
            raise serializers.ValidationError("Those passwords don't match.")
        return attrs

当我转到此视图的 url 时,它会自动生成 HTML 表单字段,我很困惑。那么,这是否意味着它使用序列化程序来生成 HTML 字段。实际上,我不明白它的请求流程是如何使用序列化器呈现 HTML 表单的。请帮助我或建议我首先要学习什么。提前致谢。

【问题讨论】:

    标签: python django django-forms django-rest-framework django-templates


    【解决方案1】:

    如果基于 request.accepted_renderer.format 的 DRF 响应。如果是html则返回BrowsableAPI(有模板,基于bootstrap)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-20
      • 2016-03-04
      • 1970-01-01
      • 2022-10-20
      • 2010-10-11
      • 2014-08-05
      • 2011-08-24
      • 1970-01-01
      相关资源
      最近更新 更多