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

In django-forms, how can I make the values of 'name' column of foreign database visible in the selection choices

My Django site has a database model named Status with:

 class Status(models.Model):
     x = models.ForeignKey(Person, on_delete=models.SET_NULL, null = True)

The Person database model referenced here contains attributes such as name, profile_pic etc.

In forms.py, I have:

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

class StatusForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(StatusForm, self).__init__(*args, **kwargs)

    class Meta:
            model = Status
            fields = ['x']

Now, when running the site, I get:

enter image description here

I want the name attribute of the Person to be shown in the choices instead of being shown Person object(1), Person object (2)…..

How can I make that happen?

>Solution :

From Other model instance methods[Django-doc]

Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object

In your Person model use str()[Django-doc] as

class Person(models.Model):
    name = models.charField(max_length=100)
    .....

    def __str__(self):
        return self.name 
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