I have a huge Django project I am making tweaks to. I need to have one dropdown field which automatically populates two other read-only fields in an admin page. I wish to do this without saving or refreshing the page. I want to be able to see the read-only fields instantly change as I change the dropdown selection.
Right now, I have the dropdown and the two read-only fields working, but not instantly. The read-only fields only update to match the dropdown when I save, and then open that instance again. I did this by overwriting the save method:
def save(self, *args, **kwargs):
self.firstname = self.fullname.split()[0]
self.lastname = self.fullname.split()[1]
super().save(*args, **kwargs)
I know there's a javascript onchange strategy that can do this, I'm just a little confused as to how to apply this to a Django framework to make it behave as intended. Any help would be very much appreciated.
UPDATE: I think I figured this out. In change_form.html, which is located in contrib/admin/templates/admin, one can add javascript into the after_field_sets block so that the fields are added first and then you can manipulate them by using their id's, which you can find by opening up developer view on your page. I still have to test and debug, but this code seems to work:
<script type="text/javascript">
document.getElementById("id_firstname").readOnly = true;
document.getElementById("id_lastname").readOnly = true;
(function($){
$("select").change(function(){
document.getElementById("id_firstname").value = document.getElementById("id_fullname").value.split(" ")[0]
document.getElementById("id_lastname").value = document.getElementById("id_fullname").value.split(" ")[1]
}).change();
})(django.jQuery);
</script>
Note: you need to put a copy of your edited change_form.html in templates/admin/your-app/your-model and the Django framework will use this version of change_form.html as an override to the original for the particular model that you specify in your folder structure.