Django REST Framework does not display value in PUT form

Yesterday I posted a question and found a solution to this problem. However, the solution caused another problem.
Please take a look at the question, so I do not need to duplicate the content.

In the view API, the value of class_name is not displayed in the PUT form.

The HTML presented is as follows:

<div class="form-group "> <label class="col-sm-2 control-label "> Class </label> <div class="col-sm-10"> <input name="class_name" class="form-control" type="text"> </div> </div> 

For other fields, it displays the value correctly, for example:

 <div class="form-group "> <label class="col-sm-2 control-label "> Order </label> <div class="col-sm-10"> <input name="order" class="form-control" value="Carnivora" type="text"> </div> </div> 

Here are screenshots illustrating the problem: enter image description here enter image description here

You can see that the value for the key "class" is. The name of the input element, as well as the name of the field in the model, is "class_name".

I poked the source code and found out that the form appears in the renderers.py file in the following order:

  • In the BrowsableAPIRenderer class, the BrowsableAPIRenderer method creates a form and calls the get_rendered_html_form method.
  • The get_rendered_html_form method calls the render_form_for_serializer method.
  • The render_form_for_serializer method calls the render method of the HTMLFormRenderer class.

But I still don’t know where to intervene and what I have to change.

I also tried to implement the to_internal_value method in the serializer, but this is only for deserialization and has nothing to do with the rendering of the form.

Does anyone have an idea where the problem lies and what can be done?

UPDATE

I created a GitHub repo with code. You can clone it or develop it and try to help me.
Thank you very much!

0
source share
1 answer

I developed another way that seemed to work just fine for me. This should have defined the class field for the serializer outside the class:

 class SpeciesSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Species fields = ( 'url', 'id', 'canonical_name', 'slug', 'species', 'genus', 'subfamily', 'family', 'order','class', 'phylum', 'ncbi_id', 'ncbi_taxonomy', ) read_only_fields = ('slug',) extra_kwargs = { 'url': {'lookup_field': 'slug'} } SpeciesSerializer._declared_fields["class"] = serializers.CharField(source="class_name") 

After that, both Raw Data and the HTML form look great:

HTML Form

Initial data

+3
source

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


All Articles