Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Multi value on ModelMultipleChoiceField

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.

like image 462
Budi Gunawan Avatar asked Oct 29 '22 10:10

Budi Gunawan


1 Answers

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.

like image 164
Bijoy Avatar answered Nov 13 '22 16:11

Bijoy