Home > Software design >  In django-forms, how can I make the values of 'name' column of foreign database visible in
In django-forms, how can I make the values of 'name' column of foreign database visible in

Time:02-07

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:

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?

CodePudding user response:

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 

CodePudding user response:

In your Person model just add the str method as following:

class Person(models.Model):
    # Your fields here
    
    def __str__(self):
        return self.name 

That will return the name for every instance in the choicefield.

  •  Tags:  
  • Related