简体   繁体   中英

How to use ModelChoiceField in DRF?

I am trying to convert my form that was written earlier to django rest serializer but it does't work. Could you help me to solve this problem please?

this is my form:

class TripSearchForm(forms.Form):
    departure = ModelChoiceField(
        queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete")
    )
    destination = ModelChoiceField(
        queryset=Place.objects.places_for_segment(), widget=autocomplete.ModelSelect2(url="autocomplete")
    )

How to built proper serializer?

class SearchSerializer(serializers.Serializer):
   departure = serializers.RelatedField(queryset=places_models.Place.objects.all(),
                                        label='departure')
  destination = serializers.RelatedField(queryset=places_models.Place.objects.all(), 
                                         label='destination')

Assuming you have model Country

class Country(models.Model):
    name = models.CharField(max_length=60, blank=True, default='')

You could write a serializers based on that

class CountryField(serializers.PrimaryKeyRelatedField):
    def display_value(self, instance):
        return instance.name


class CountrySerializer(serializers.ModelSerializer):
    country = CountryField(queryset=Country.objects.all())

    class Meta:
        model = Country
        fields = ('name', )


class DesiredSerializer(serializers.Serializer):
    country = ColorSerializer()

Now you should be able to use your desired serialized to render choices from model either as html form for instance or whatever logic fits you better

if you want it as form

#views.py
def get(self, request):
        serializer = DesiredSerializer()
        return Response({ 'serializer': serializer }, template_name='my_model_choices_form.html')
<!-- my_model_choices_form.html -->
{% load rest_framework %}
<form action="..." method="POST">
    {% csrf_token %}
    {% render_form serializer %}
</form>

Now if you'll create instance of Country with some name it will be shown in select dropdown, display_value function can be used to customize the option output.

Hope that helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM