Django Admin - 更改外键后填充其他字段

时间:2016-01-25 19:02:23

标签: python django django-admin

我有这个型号:

class Order(models.Model):
    client = models.ForeignKey(
        Client,
        on_delete=models.CASCADE,
        related_name='orders',
        related_query_name='order',
    )

    delivery_country = CountryField('Kraj wysyłki', null=True, blank=True)
    delivery_city = models.CharField('Miasto wysyłki', max_length=255, null=True, blank=True)
    delivery_street = models.CharField('Ulica wysyłki', max_length=255, null=True, blank=True)

    billing_country = CountryField('Kraj dla faktury', null=True, blank=True)
    billing_city = models.CharField('Miasto dla faktury', max_length=255, null=True, blank=True)
    billing_street = models.CharField('Ulica dla faktury', max_length=255, null=True, blank=True)

    products = models.ManyToManyField(Product, through='OrderProduct')

class Client(models.Model):
    name = models.CharField('Imię', max_length=255)
    surname = models.CharField('Nazwisko', max_length=255)
    country = CountryField('Kraj', null=True, blank=True)
    city = models.CharField('Miasto', max_length=255, null=True, blank=True)
    street = models.CharField('Ulica', max_length=255, null=True, blank=True)

我想在Django Admin中实现这种行为: 每次更改Order.client后,我都要预填充其他字段:

  • Order.delivery_country = client.country
  • Order.delivery_city = client.city
  • Order.delivery_street = client.street
  • Order.billing_country = client.country
  • Order.billing_city = client.city
  • Order.billing_street = client.street

是否有任何包/插件可以实现此目的? 或许你有一些想法我怎么能自己做?

1 个答案:

答案 0 :(得分:0)

好的,我实现了这个目标:

JS:

(function ($) {
    $(document).ready(function(){
        $("select[name='client']").on("change", function(){
            $.ajax({
                url: "/admin/clients/"+$(this).val(),
                type: "GET",
            }).done(function(data){
                client_data = $.parseJSON(data);
                client_data = client_data[0];

                $("select[name='delivery_country']").val(client_data.fields.country);
                $("input[name='delivery_city']").val(client_data.fields.city);
                $("input[name='delivery_street']").val(client_data.fields.street);

                $("select[name='billing_country']").val(client_data.fields.country);
                $("input[name='billing_city']").val(client_data.fields.city);
                $("input[name='billing_street']").val(client_data.fields.street);
            });
        });
    });
})(django.jQuery);

并查看:

def get_client_ajax(request, id):
    return JsonResponse(serializers.serialize('json', Client.objects.filter(id=id)), safe=False)