koddr
koddr

Reputation: 784

How to make for models with ForeignKey (autocomplete_fields) multi-step choices in standard Django Admin?

Question for Django 2.0 with Select2 on the box. How to make for models with ForeignKey (autocomplete_fields) multi-step choices in standard Django Admin?

My tours app is:

tours/models.py:

class Tours(models.Model):
    country = models.ForeignKey(Countries, on_delete=None, default=None)
    resort = models.ForeignKey(Resorts, on_delete=None, null=True, default=None)

tours/admin.py:

@admin.register(Tours)
class ToursAdmin(admin.ModelAdmin):
    list_display = ('country', 'resort',)
    autocomplete_fields = ('country', 'resort',)

And this is my countries app:

countries/models.py:

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

class Resorts(models.Model):
    name = models.CharField(max_length=255)
    country = models.ForeignKey(Countries, on_delete=models.CASCADE, default=None)

countries/admin.py:

class ResortsInlineAdmin(admin.StackedInline):
    model = Resorts

@admin.register(Countries) 
class CountriesAdmin(admin.ModelAdmin):
    list_display = ('name',)
    search_fields = ('name',)
    inlines = [ResortsInlineAdmin,]

@admin.register(Resorts)
class ResortsAdmin(admin.ModelAdmin):
    list_display = ('name', 'country',)
    search_fields = ('name',)

Would be nice after choose value in Country field — leave in Resort field only values that relate to this Country (inlines option in countries/admin.py).

Similar demo with PHP + jQuery.

Upvotes: 2

Views: 941

Answers (1)

koddr
koddr

Reputation: 784

Answer is too simple, but I've many hours in Google.

First, added extra context to tours/admin.py (ModelAdmin.change_view()):

# tours/admin.py

@admin.register(Tours)
class ToursAdmin(admin.ModelAdmin):
    list_display = ('country', 'resort',)
    autocomplete_fields = ('country', 'resort',)

    def change_view(self, request, object_id, form_url='', extra_context=None):
        extra_context = extra_context or {}
        extra_context['resort_to_country'] = Resorts.objects.all().values_list('pk', 'country_id')
        return super().change_view(
            request, object_id, form_url, extra_context=extra_context,
        )

Next, improve templates/admin/tours/add_form.html with JavaScript, like this:

// on bottom, into <script></script> tag:

var resort_to_country = [
    {% for i in resort_to_country %}
        ['{{ i.country }}', {{ i.pk }}, '{{ i.name }}'],
    {% endfor %}
];

var resorts_select_field = django.jQuery('#id_resort');
var countries_select_field = django.jQuery('#id_country');

countries_select_field.on('change', function () {
    resorts_select_field.empty();
    resort_to_country.forEach(function (item) {
        if (item[0] === countries_select_field.find(':selected').text()) {
            resorts_select_field.append(django.jQuery('<option></option>').attr('value', item[1]).text(item[2]));
        }
    });
});

That's all.

Upvotes: 1

Related Questions