djangoformsmodelchoicefield

ModelChoiceField lists tuples instead of simple values


I have a django form with a ModelChoiceField input and it lists the result as tuples instead of simple values.

I have no clue on how to do it.

DJANGO
class PayThis(forms.Form):
   amount = forms.FloatField(required=False)
   cost2  = forms.FloatField(required=False)
   year = forms.ModelChoiceField(required=False,queryset=AnAgricol.objects.values_list('anul').all())

 HTML
 <option value="(2019,)">(2019,)</option>

I expect to get this: < option value="2019">2019< /option >


Solution

  • A ModelChoiceField deals, like the name suggests, with model objects. You thus can not use values_list here.

    Your Form thus should define something like:

    class PayThis(forms.Form):
        amount = forms.FloatField(required=False)
        cost2  = forms.FloatField(required=False)
        year = forms.ModelChoiceField(required=False, queryset=AnAgricol.objects.all())

    You can override the __str__ to return a string representation of the year, like:

    AnAgricol(models.Model):
        anul = models.IntegerField()
    
        def __str__(self):
            return str(self.anul)

    If the year however is not something to represent AnAgricol, then you could use a ChoiceField [Django-doc], like:

    class PayThis(forms.Form):
        amount = forms.FloatField(required=False)
        cost2 = forms.FloatField(required=False)
        year = forms.ChoiceField(required=False, choices=[])
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.fields['year'].choices = [
                (yr, yr) for yr
                in AnAgricol.objects.values_list('anul', flat=True).distinct()
            ]