This is old, but it can be quite a puzzle, and the accepted answer did not address the true issue for me.
The question, as I understand it, is how to pre-fill data on the related model's admin form, which pops up after you click the green +
("Add another") next to a widget for a ForeignKey
or ManyToManyField
. This is illustrated below.

As suggested in the (currently) accepted answer, as well as here, this can be achieved by adding URL parameters for each of the fields that you want to pre-fill. This is also illustrated in the image.
The question that remains unanswered, however, is:
How, exactly, can we add these URL parameters to the URL used by the +
("Add another") link?
Assuming the pre-filled values depend on a the current state of the form on the client side, e.g. the selected organization
in the image above, I suppose it makes sense to use JavaScript.
Note: If the pre-filled values do not depend on the form state, nor on the current request, other options might be more appropriate.
Here's a minimal example that was used to create the image above:
models.py: (we put the admin stuff in here as well for convenience)
from django.db import models
from django.contrib import admin
class Organization(models.Model):
pass
class Participant(models.Model):
organization = models.ForeignKey(to=Organization, on_delete=models.CASCADE)
class Event(models.Model):
organization = models.ForeignKey(to=Organization, on_delete=models.CASCADE)
participants = models.ManyToManyField(to=Participant)
admin.site.register(Organization)
admin.site.register(Participant)
admin.site.register(Event)
Now we extend the Django admin change_form
template (based on the docs) for our Event
model with a little bit of JavaScript.
Follow these instructions to set-up your templates folder, and don't forget to add you templates folder to DIRS
in settings.TEMPLATES
.
templates/admin/my_app/event/change_form.html:
{% extends 'admin/change_form.html' %}
{% load static %}
{% block admin_change_form_document_ready %}
{{ block.super }}
<script type="text/javascript">
var add_participant_url = document.getElementById("add_id_participants").href;
var organization = document.getElementById("id_organization")
organization.onchange = function() {
document.getElementById("add_id_participants").href =
add_participant_url + "&organization=" + organization.value;
};
</script>
{% endblock %}
DISCLAIMER: I have limited experience with JavaScript, so any suggestions for improvement are welcome.
Basically, whenever the user changes the selected organization on the "Change event" form, the URL for the "Add another participant" (+) link is updated with the selected value, so the organization field on the "Add participant" form will be pre-filled.