Steno
Steno

Reputation: 17

Django Form - Select dropdown

How do I Output both "id_no" and "name" [id_no - name] combined in dropdown select form. Can it be done directly to the form using {{form}} only.

Model:
class Employee(models.Model):
  id_no = models.CharField(unique = True,max_length=6)
  name = models.CharField(max_length=100)

Form:
class EmployeeForm(forms.ModelForm):
  class Meta:
   model = Employee
   fields = __all__
    
    
    

Upvotes: 1

Views: 103

Answers (1)

dani herrera
dani herrera

Reputation: 51645

Yes, it be done directly to the form using {{form}} implementing str :

class Employee(models.Model):
    id_no = models.CharField(unique = True,max_length=6)
    name = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.id_no} - {self.name}"

But not on EmployeeForm because this form doesn't have a drop down to pick an employee. You will see it on a modelFrom for a form with a ForeignKey to employee.

Upvotes: 2

Related Questions