Reputation: 125
I am trying to implement a form that uses two models connected through a foreign key. Below is my current setup:
Primary Model:
class Firstlist(models.Model):
TBlname = models.CharField(max_length=100)
def __str__(self):
return self.name
Second Model:
class SecondList(models.Model):
Status = models.CharField(max_length=100)
Tblnameref = models.ForeignKey(Firstlist)
def __str__(self):
return self.name
Form:
class MainForm(forms.ModelForm):
class Meta:
model = SecondList
fields = ('Tblnameref','Status')
def __init__(self,*args,**kwargs):
super(SecondList,self).__init__(*args,**kwargs)
self.fields['Tblnameref'].empty_label = '-- Select --'
Template:
<form action="" method="POST">{% csrf_token %}
{{form.Tblnameref}}
<button>Validate</button>
{{form.Status}}
<button>Validate</button>
</form>
However when I test this, the values in drop down show up as "Tblnameref object (1)" instead of the actual value.
Can someone please advise how to fix this so that the drop down shows actual value than the object. Thank you for the help
Upvotes: 2
Views: 2804
Reputation: 691
This is very normal, Your model the field Tblnameref of the model SecondList, stores only "id"s of Firstlist (primary key). so to have values instead, you must do a query to Firstlist inorder to get the id '1'
Firstlist.objects.get(id__exact="yourvariable_Tblnameref").TBlname
Upvotes: 0
Reputation: 2334
When you use the following code
def __str__(self):
return self.name
there should be a field name
in your model but it seems you don't have it.
Change the __str__
method in your Firstlist model.
class Firstlist(models.Model):
TBlname = models.CharField(max_length=100)
def __str__(self):
return self.TBLname
The __str__
function is used to add a string representation of a model's object, here it will show the value of TBLname
, you can change it as per your requirement.
Do the same for second model also as it seems it doesn't have a name
field either, try using a field already present in the model.
See documentation for more information.
Upvotes: 2