1

I would like to create a custom horizontal filter inside Django admin. My use case looks like this. I am working on a Testmanagment tool. You got "Projects" like websiteA or WebsiteB. Every Project has its own Elements/Groups. E.g WebsiteA got "Dashboard" and "Login" and WebsiteB has "Users" and "Orders".

If I am creating a new Testcase I would like to choose the Project first and offer a filtered list to all corresponding Elements for that project.

I don't want to get all Elements/Groups for a new Testcase.

My code looks something like this:

Forms.py:

class TestCaseForm(forms.ModelForm):

@staticmethod
def groupSmartFilter():
    return GroupModel.objects.filter(id=2) #working fine so far
    but should be something like
    return Projects.objects.filter(projectname=<$project_from_dropdown>).groups()

def __init__(self, *args, **kwargs):
    forms.ModelForm.__init__(self, *args, **kwargs)
    self.fields['groups'].queryset = TestCaseForm.groupSmartFilter()



class Meta:
    model = TestCaseModel
    fields = ('name', 'TestcaseNummer', 'project','groups', 'description' , 'url' )

admin.py

class TestCaseAdmin(CompareVersionAdmin):
form = TestCaseForm
filter_horizontal = ('groups',)
Nils Zenker
  • 659
  • 7
  • 11
  • Is the selection of project and group happening on the same page? Or is the project_from_dropdown value determined before the form is loaded? – Nico Griffioen Oct 28 '19 at 08:45
  • it is handled on the same page (standard admin new item creation page) This might be bummer. It would be so much easier ir one need to choose the Project first. – Nils Zenker Oct 29 '19 at 11:01
  • Yeah, to implement this you'd probably need to do an AJAX request from your form upon choosing the project, and fill in the choices there, which is quite a lot of work. You could try making all fields on the model except project optional, and have two forms, one where you only select project and create the TestCase, and one were you edit the TestCase, and select all other values. You can then limit choices with the method outlined in [this answer](https://stackoverflow.com/questions/232435/how-do-i-restrict-foreign-keys-choices-to-related-objects-only-in-django) – Nico Griffioen Oct 29 '19 at 11:47

0 Answers0