How to change the browser API form

I am currently creating a UserRegistration view that should display a form with password / password confirmation fields. The problem is that only fields that appear in the model definition are displayed in the API browser.

  • How do I customize the form 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 between an input serializer and an output serializer?

+6
source share
2 answers

Well, you must first define this in the View or ViewSet that you are using. The serializer does not control the API browser in this way, it simply handles the transfer of objects from the native to some serialized format and vice versa.

Since you are not mentioning, I'm going to assume that you are using http://django-rest-framework.org/

The specific piece of documentation you can check out is: http://django-rest-framework.org/api-guide/viewsets.html#modelviewset

0
source

The Django Rest Framework actually uses the regular Django Forms, which are displayed in the Browsable API view.

You can control the appearance of the form by changing the renderer used: http://www.django-rest-framework.org/api-guide/renderers#browsableapirenderer

For instance:

 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 change the form after creating it, I have not tried it. If not, you can rewrite the entire function that creates the form. I would add form fields, which would be preferable.

0
source

Source: https://habr.com/ru/post/948776/


All Articles