0

i want to get a list of users and populate it in the select dropdown, but the values don't format properly.

[models.py]
from django.contrib.auth.models import User

class Post(models.Model):
  title = models.CharField()
  author = models.ForeignKey(User, on_delete= models.CASCADE)

[forms.py]
from django.contrib.auth.models import User

class PostForm(forms.ModelForm):
  class Meta:
    model = Post
    fields = ['title','author']

    widgets = {
      'author': Select(attrs={'style': 'width: 400px;'}),
    }

  def __init__(self, *args, **kwargs):
    super(PostForm, self).__init__(*args, **kwargs)
    self.fields['author'].queryset = User.objects.values_list('first_name')

and this is what Select dropdown for Author shows:

Author

how do i make it shown like below:

-----
Admin
John
2
  • Why are you setting the author queryset to a values_list of last names? This is your problem Commented Apr 25, 2020 at 2:04
  • By default, if i don't specify the queryset, the Select dropdown would display the username by default, that's not what i want. I want to override the username and display the names instead. Commented Apr 25, 2020 at 3:01

1 Answer 1

1

To override the label used in a ModelChoiceField you need to create a subclass and override label_from_instance. At the end of the docs for the field

from django.forms import ModelChoiceField

class UserChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return obj.first_name

class PostForm(forms.ModelForm):

   author = UserChoiceField(User.objects.all())

   class Meta:
       model = Post
       fields = ['title','author']

       widgets = {
          'author': Select(attrs={'style': 'width: 400px;'}),
       }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.