Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

1.5K
Views
Custom Dependent Dropdown menu inside the Django admin

I have a project foreign key in by Phase model. I'm having hard time Create a dependent drop-down list inside my Django admin page.

I want to when user select a project from (project drop-down) phase of that project show in second dop-down

What would be the best way to achieve this?

It would be great if the dropdowns filter items based on the value of its parent.

enter image description here

class Project(models.Model):
    name                    = models.CharFieldmax_length = 100, unique= True)
    short_name              = models.CharField(max_length= 4, unique= True)
    slug                    = models.SlugField(max_length= 100, allow_unicode=True, null=True, editable= False)
    location                = models.OneToOneField(Location, on_delete = models.SET_NULL, null= True, blank= False, verbose_name= 'موقعیت')
    start_date              = models.DateField(default= timezone.now, null= True, blank= True)      
    end_date                = models.DateField(default= timezone.now, null= True, blank= True)
    duration                = models.IntegerField(default= 0, editable= False)

class Phase(models.Model):
    title                = models.CharField(max_length= 20)

class ProjectPhase(models.Model):
    project                 = models.ForeignKey(Project, on_delete= models.CASCADE, related_name= 'phase')
    phase                   = models.ForeignKey(Phase, on_delete=models.CASCADE, related_name= 'project')
    start_date              = models.DateField(default= timezone.now)      
    end_date                = models.DateField(default= timezone.now)
    duration                = models.IntegerField(default= 0, editable= True)
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

1. import a js media file in ModelAdmin for Generaldata:

class YourModelAdmin(admin.ModelAdmin):    
    form = YourModelForm
    #list_display = ['your fields',]
    class Media:
        js = ("yourapp/selectajax.js",)

admin.site.register(YourModel, YourModelAdmin)

2. create a new js file which saved yourproject/yourapp/static/yourapp/ directory or another proper directory.

jQuery(function($){
    $(document).ready(function(){
        $("#id_project_select").change(function(){
            // console.log(obj.currentTarget.value);
            $.ajax({
                url:"/get_phases/",
                type:"POST",
                data:{project: $(this).val(),},
                success: function(result) {
                    console.log(result);
                    cols = document.getElementById("id_phase_select");
                    cols.options.length = 0;
                    for(var k in result){
                        cols.options.add(new Option(k, result[k]));
                    }
                },
                error: function(e){
                    console.error(JSON.stringify(e));
                },
            });
        });
    }); 
});

3. create a view to process ajax

@login_required
def get_phases(request):
    project = request.POST.get('project')
    phases = {}
    try:
        if project:
            prophases = Project.objects.get(pk=int(project)).phase
            phases = {pp.phase.title:pp.pk for pp in prophases}
    except:
        pass
    return JsonResponse(data=phases, safe=False)

4. add 'get_phases/ to urlpatterns.

Notice that you should modify some codes as your need.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!