Home > Mobile >  Django Form - Select dropdown
Django Form - Select dropdown

Time:12-17

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__
    
    
    

CodePudding user response:

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.

  • Related