Django admin popup window not closed after the form submitted successfully

I have a computed field(add_workplace_link) in display_list to open a popup window in order to add new instance of Workplace model. The popup window opens as expected. After form submitted successfully, the window remains open an empty page.

models.py

from django.db import models

class Company(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

class Workplace(models.Model):
    title = models.CharField(max_length=255)
    company = models.ForeignKey(Company, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

admin.py

@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
    list_display = ['name', 'add_workplace_link']

    def add_workplace_link(self, obj):
        # Generate the URL to the Workplace add form with the company preselected
        url = reverse('admin:appname_workplace_add') + f'?company={obj.pk}'
        return format_html('<a href="{}">Add Workplace</a>', url)

    add_workplace_link.short_description = 'Add Workplace'


class WorkplaceAdmin(admin.ModelAdmin):
    list_display = ['title', 'company']

    def get_form(self, request, obj=None, **kwargs):
        form = super().get_form(request, obj, **kwargs)
        # Check if we have the company parameter in the URL and set the initial value
        if 'company' in request.GET:
            company_id = request.GET.get('company')
            form.base_fields['company'].initial = company_id
        return form

Here are images for each step:

1. Admin changelist for Company model

2. popup window opened as expected

3. popup window remains open after form submitted successfully

I already checked to make sure RelatedObjectLookups.js is loaded in popup window. I expect the popup window close automatically after form submitted successfully. What is missing?

Back to Top