How do I change an input field for foriegn key to show name vs. id

I have a model with a foriegn key and want the input select to display the name in the foriegn model instead of the id.

ok more details and what I have tried. Two models, Client and Master.

class Client(models.Model):
id = models.BigAutoField(primary_key=True),
clientName = models.CharField(max_length=200, blank=False, null=True)
clientEmail = models.CharField(max_length=200, blank=False, null=True)
clientPhone = models.CharField(max_length=200, blank=False, null=True)
clientCompany = models.CharField(max_length=200, blank=False, null=True)

def __str__(self):
    return self.clientName

and Master abbreviated

class Master(models.Model):
id = models.BigAutoField(primary_key = True)
client = models.ForeignKey(Client, on_delete=models.CASCADE,null=True)

user_name = models.CharField(max_length=500, blank=False, null = True)

def str(self):
return self.user_name

def clientaccount_name(self):
    return self.client.clientName

trying the admin change master page I get

AttributeError at /admin/kdconnector/master/

‘NoneType’ object has no attribute ‘clientName’

Request Method: GET
Request URL: http://localhost:8000/admin/kdconnector/master/
Django Version: 4.1.7
Exception Type: AttributeError
Exception Value: ‘NoneType’ object has no attribute ‘clientName’
Exception Location: C:\Users\MikeOliver\KDConnectorSite\kdconnectorsite\kdconnector\models.py, line 522, in clientaccount_name

I extrapolated this solution from an older Stack Overflow post.

Ok Ken where would your recommended iterator documenation example go?

See the iterator attribute in the ModelChoiceField docs.

Thanks Ken, I expanded my post with more details. I looked at the iterator documentation, but I failed to see where to use it.

  • Can we at least show your views.py files code?

on your class Master:

def __str__ (self):
return self.user_name

I think you have to explicitly tell Django, you are working with string here:

def clientaccount_name(self):
    return str(self.client.clientName)

  • OR you do that with our old-time buddy, like this:
def __str__(self):
    return self.client.clientName

If you error continues, kindly show us your views.py and forms.py code snippet regarding your Master, and Client.