Filling values ​​in django-admin based on foreign key selection

I have a model with a link to a foreign key that looks something like this.

class Plan(models.Model): template = models.ForeignKey(PlanTemplate) throttle = models.IntegerField(default=10) rate_limit = models.BigIntegerField(default=60) 

and foreign key model:

 class PlanTemplate(models.Model): name = models.CharField(max_length=50) throttle = models.IntegerField(default=10) rate_limit = models.BigIntegerField(default=60) 

I would like the throttle and rate_limit on the plan administration page to be automatically populated when you select PlanTemplate. Is this something convenient for django-admin, or do I need to override the admin template and add custom javascript?

I am running Django 1.2.4.

+4
source share
2 answers

I found a way to do this, but it should have included javascript, which was really pretty straight forward. I created a change_form.html file in the templates / admin / billing / directory, which looked like this.

 {% extends "admin/change_form.html" %} {% block extrahead %} <script src="{{MEDIA_URL}}js/jquery.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { $('#id_template').change(function() { $.ajax({ type: 'POST', url: "{% url get_template_info %}", data: {'template_id': $('#id_template').val()}, success: function(data, _status) { $('#id_throttle').val(data.throttle); $('#id_rate_limit').val(data.rate_limit); $('#id_product').val(data.product); $('#id_tier_group').val(data.tier_group); }, dataType: "json" }); }); }); </script> {% endblock %} 

which displays a view that simply takes the passed id, requests it and returns it to the call. It works like a charm.

+3
source

This would be easy to do if you made it a two-step process. Perhaps having add_view , which has only 1 field, template .

Otherwise, you will have to use JavaScript and set up a view that returns template data.

Here's a simple solution using a model administrator and a two-step form:

 class MyAdmin(ModelAdmin): # ... def add_view(self, request, form_url='', extra_context=None): self.fields = ['template'] # add view has only 1 field. return super(MyAdmin, self).add_view(request, form_url, extra_context) def save_model(self, request, obj, form, change): if not change: # if adding... populate defaults. obj.throttle = obj.template.throttle obj.rate_limit = obj.template.rate_limit obj.save() 
0
source

Source: https://habr.com/ru/post/1343878/


All Articles