Budi Gunawan
Budi Gunawan

Reputation: 101

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.

Upvotes: 5

Views: 395

Answers (2)

Benyamin Jafari
Benyamin Jafari

Reputation: 34216

In the User class, you should add the methods given below:

def __unicode__(self):
    return "{} - {}".format(self.id, self.name)

def __str__(self):
    return "{} - {}".format(self.id, self.name)

NOTE: No need for __unicode__() if using Python3.x.

Upvotes: 0

Bijoy
Bijoy

Reputation: 1131

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.

Upvotes: 2

Related Questions