如何修改可浏览的API表单 [英] How to modify Browsable API form

查看:88
本文介绍了如何修改可浏览的API表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在创建一个UserRegistration视图,该视图应显示带有密码/确认密码字段的表单。问题在于Browsable API仅显示模型定义中出现的字段。

Currently, I am creating a UserRegistration view, which should display form with password/confirm password fields. The problem is that the Browsable API displays only fields which occur in the model's definition.


  • 我应该如何调整表格以便才能添加自定义字段?

  • How should I tweak the form so that to be able to add custom fields?

class UserRegistrationSerializer(serializers.ModelSerializer):

    password = serializers.CharField(
        max_length=128,
        widget=widgets.PasswordInput,
        label=_('Password')
    )
    password_confirm = serializers.CharField(
        max_length=128,
        widget=widgets.PasswordInput,
        label=_('Confirm password')
    )

    class Meta:
        model = User
        fields = ('id', 'name', 'username', 'email', 'password', 'registration_date')

    def validate(self, attrs):
        if attrs.get('password') and attrs.get('password_confirm'):
            if attrs['password'] != attrs['password_confirm']:
                raise serializers.ValidationError(_("Passwords do not match"))
        return attrs


  • 另外,区分输入序列化程序和输出序列化程序的最佳方法是什么?

  • Also, what is the best way to distinguish the input serializer from the output serializer?

    推荐答案

    Django Rest Framework实际上使用呈现在Browsable API视图中的普通Django表单。

    Django Rest Framework actually uses normal Django Forms that are rendered into the Browsable API view.

    您可以通过修改Renderer来控制表单的外观使用的: http://www.django-rest-framework.org/api -guide / renderers#browsableapirenderer

    You can control the look of the form by modifying the Renderer that is used: http://www.django-rest-framework.org/api-guide/renderers#browsableapirenderer

    例如:

    class MyBrowsableAPIRenderer(BrowsableAPIRenderer):
        # either
        def get_context(self, *args, **kwargs):
            context = super(MyBrowsableAPIRenderer, self).get_context(*args, **kwargs)
            context["post_form"] = django.form.Form()  # modify form here          
    
        # or
        def get_rendered_html_form(self, view, method, request):
            # do things here to create full Form
    
    @renderer_classes((JSONRenderer, MyBrowsableAPIRenderer)):
        class MyViewSet(GenericViewSet):
            pass
    

    我不知道您是否可以修改表单创建后,我还没有尝试过。如果没有,您可以重写创建表单的整个函数。我可以添加表单字段,这将是更好的选择。

    I do not know if you can modify a Form after it has been created, I haven't tried. If not, you could rewrite the entire function that creates the form. I you could add Form fields, that would be preferable.

    这篇关于如何修改可浏览的API表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆