Django ModelForm - form display values

后端 未结 1 1609
孤独总比滥情好
孤独总比滥情好 2020-12-22 12:41

I have a model:

class SchedulerProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    first_name = models.CharField(max_length=50)
    la         


        
相关标签:
1条回答
  • 2020-12-22 13:14

    Subclass ModelMultipleChoiceField and override label_from_instance.

    from django.forms import ModelMultipleChoiceField
    
    class SchedulerProfileChoiceField(ModelMultipleChoiceField):
        def label_from_instance(self, obj):
            return "%s %s" % (obj.first_name, obj.last_name)
    

    Then use your multiple choice field in the model form.

    class OfficialProfileForm(forms.ModelForm):
        schedulers = SchedulerProfileChoiceField(queryset=SchedulerProfile.objects.all())
    
    0 讨论(0)
提交回复
热议问题