surfi
surfi

Reputation: 1591

Concatenate value of two models by overriding ModelForm and ModelChoiceField

To show just the just the related Projects in a ForeignKey Selectbox in Django AdminForm, i customized my ActionAdmin Model with a ActionAdminForm class. to preselect values i used a class like posted here https://stackoverflow.com/a/9191583/326905. Thanks a lot, this works really fine.

But when user does not navigate form Customer -> Project -> Action and navigates directly to Actions in django admin i want to display the values in the selectbox for foreignkey project in ActionAdmin Form formatted like this:

Customername1 - Projectname1
Customername1 - Projectname2
Customername2 - Projectname3

My question is, how could i override self.fields["project"]
in the else case in the code below,
so that i get selectbox values concatenated from
Project.customer.name and Project.name?

class ActionAdminForm(ModelForm):
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(ActionAdminForm, self).__init__(*args, **kwargs)
        if self.request.GET.get('project'):
            prj = Project.objects.get(id=self.request.GET.get('project'))
            self.fields["project"].queryset = Project.objects.filter(customer = prj.customer)
        else:


           self.fields["project"] = ProjectModelChoiceField(Project.objects.all().order_by('name'))

    class Meta:
        model = Action

Upvotes: 2

Views: 725

Answers (1)

surfi
surfi

Reputation: 1591

I got the solution. Yeah. First i got always error when i tried to use just self.fields["project"], but now it works. I put it into else and wrote a ProjectModelChoiceField like below, influenced by this description: http://bradmontgomery.blogspot.de/2009/01/custom-form-for-djangos-automatic-admin.html

class ProjectModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "%s - %s"%(obj.customer.name, obj.name)

Upvotes: 1

Related Questions