[英]Django Admin - populate other fields after changing foreignkey
I have this model: 我有这个模型:
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)
And I would like to achieve this behaviour in Django Admin: After every change of Order.client
I want to prepopulate other fields like this: 我想在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
Is there any package/plugin to achieve this? 是否有任何软件包/插件来实现这一目标? Or maybe you have some ideas how I could do it myself?
或者,也许您有一些想法,我自己可以如何做?
Ok I achieved this: 好的,我做到了:
(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.