views:

20

answers:

1

Hey; i have a model using user as a forgignKey. and in the admin, i need it show as full name instread of username. then i applied

class CollaboratorInLine(admin.StackedInline):
    model = Collaborator
    #list_display = ('collaborator__collaborator_first_name')
    extra = 0
    form =CollaboratorForm
    #raw_id_fields=("collaborator",)

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs):
        field = super(CollaboratorInLine, self).formfield_for_foreignkey(
                                                db_field, request, **kwargs)
        if db_field.rel.to == User:
            field.label_from_instance = self.get_user_label
        return field
    def formfield_for_manytomany(self, db_field, request=None, **kwargs):
        field = super(CollaboratorInLine, self).formfield_for_manytomany(
                                                db_field, request, **kwargs)
        if db_field.rel.to == User:
            field.label_from_instance = self.get_user_label
        return field
    def get_user_label(self, user):   
        name = user.get_full_name()  
        return name

it works fine as a dropdown list with fullnames. then i want to sort them in alphabetical order. then i appplied

class CollaboratorForm(forms.ModelForm):
    collaborator = forms.ModelChoiceField(queryset=User.objects.order_by('first_name'))
    #assert False,collaborator
    class Meta:
        model = Collaborator

as this applied. the full names becomes username again. if i remove it, it becomes full names. so how can i keep both features?

thanks

A: 

Try subclassing ModelChoiceField and override the label_for_instance method to display the full name.

class MyModelChoiceField(ModelChoiceField): 
    def label_from_instance(self, obj): 
        return obj.get_full_name()

Then use the new field in your model form.

class CollaboratorForm(forms.ModelForm):
        collaborator = MyModelChoiceField(queryset=User.objects.order_by('first_name'))
        #assert False,collaborator
        class Meta:
            model = Collaborator
Alasdair
Hey Alasdair; it works for CollaboratorInLine. but how about the submitter in the report ,whcih is not a inline as followingclass Report(models.Model): team = models.ForeignKey(Team) project = models.CharField(max_length=255) summary = models.TextField() submitter = models.ForeignKey(User, editable=True, related_name='report_submitter')
Grey
i tried the same method. but it didnt work for submitter
Grey
my bad i forgot to assign the form. thanks Alasdair it works perfectly.
Grey