How to do custom display and auto-select in django admin multi-select field?

Posted by rsp on Stack Overflow See other posts from Stack Overflow or by rsp
Published on 2010-04-23T04:17:18Z Indexed on 2010/04/23 4:23 UTC
Read the original article Hit count: 492

I'm new to django, so please feel free to tell me if I'm doing this incorrectly. I am trying to create a django ordering system. My order model:

class Order(models.Model):
    ordered_by = models.ForeignKey(User, limit_choices_to = {'groups__name': "Managers", 'is_active': 1})

in my admin ANY user can enter an order, but ordered_by must be someone in the group "managers" (this is the behavior I want).

Now, if the logged in user happens to be a manager I want it to automatically fill in the field with that logged in user. I have accomplished this by:

class OrderAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
    if db_field.name == "ordered_by":
        if request.user in User.objects.filter(groups__name='Managers', is_active=1):
            kwargs["initial"] = request.user.id
        kwargs["empty_label"] = "-------------"
        return db_field.formfield(**kwargs)
    return super(OrderAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

This also works, but the admin puts the username as the display for the select box by default. It would be nice to have the user's real name listed. I was able to do it with this:

class UserModelMultipleChoiceField(forms.ModelMultipleChoiceField):
    def label_from_instance(self, obj):
        return obj.first_name + " " + obj.last_name
class OrderForm(forms.ModelForm):
    ordered_by = UserModelChoiceField(queryset=User.objects.all().filter(groups__name='Managers', is_active=1))

class OrderAdmin(admin.ModelAdmin):
    form = OrderForm

My problem: I can't to both of these. If I put in the formfield_for_foreignkey function and add form = OrderForm to use my custom "UserModelChoiceField", it puts the nice name display but it won't select the currently logged in user. I'm new to this, but my guess is that when I use UserModelChoiceField it "erases" the info passed in via formfield_for_foreignkey. Do I need to use the super() function somehow to pass on this info? or something completely different?

© Stack Overflow or respective owner

Related posts about django-admin

Related posts about django-forms