Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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__
    
    
    

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading