models.py
class User(models.Model):
id = models.CharField(max_length=255)
name = models.CharField(max_length=255)
desc = models.TextField()
created_at = models.DateTimeField(auto_now=True)
updated_at = models.DateTimeField(auto_now_add=True, null=True)
def __str__(self):
return self.user.name
my forms.py
class PostsForm(forms.ModelForm):
user = forms.ModelMultipleChoiceField(
queryset=User.objects.all()
)
class Meta:
model = Posts
fields = '__all__'
On my code above my form look like this:
+------------+
|Select + |
+------------+
|John Doe |
|Jessica |
|Jessica |
|Alex Joe |
+------------+
Hovewer that not what I want since possible multiple name, and I know that value come from def __str__
on my model.
How to add another str so on my field will be:
+---------------------+
|Select + |
+---------------------+
| 012931 - John Doe |
| 012932 - Jessica |
| 012933 - Jessica |
| 012934 - Alex Joe |
+---------------------+
Its contain id + name on dropdown, or also other information.
In User
model on __str__
you can do as explained in doc.
def __str__(self):
return "{} - {}".format(self.id, self.user.name)
Here is an example of the self.id
, you can get any value there like self.name
etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With