Search code examples
djangomodelchoicefield

Django ModelChoiceField shows Customers objects(1) etc on list, how do i get it to show name of customers?


models.py

class Customers(models.Model):
    Name = models.CharField(max_length=100)

class Staff(models.Model):
    Name = models.CharField(max_length=100)

class Cereals(models.Model):
    Name = models.CharField(max_length=100)
    Operator = models.CharField(max_length=100)

forms.py

class EditCereals(forms.ModelForm):
    class Meta:
        model = Cereals
        fields = ['Name', 'Operator']

    widgets = {
        'Operator': Select(),
        'Name': Select(),
    }

    def __init__(self, *args, **kwargs):
        super(EditCereals, self).__init__(*args, **kwargs)
        self.fields['Name'] = forms.ModelChoiceField(queryset=Customers.objects.all().order_by('Name'))
        self.fields['Operator'] = forms.ModelChoiceField(queryset=Staff.objects.all().order_by('Name'))

When i run the form 'Name' shows Customers Objects (1), Customers objects (2), etc and same with 'Operator' it shows Staff Objects (1), Staff Objects (2), etc

How do i get it to show the actual names, eg Bill, Fred,


Solution

  • You should use def __str__()... method. This method works for the string representation of any object.

    Example

    class Customers(models.Model):
        name = models.CharField(max_length=100)
        
        def __str__(self):
            return self.name
    

    And please name you instance variable with small letters with underscore. Captial cases should be used for classes only.