Django Admin: want to prepopulate some fields when

2020-07-13 17:22发布

问题:

In the Django Admin I want to use data from the current record to populate fields for a foreign key record when I click the add (+) button next to the drop-down list.

For example, I am viewing an instance of X which has fields for a, b, and c and a foreign key Y. Y also has fields for a, b, and c, so when I click on the "add" button on the X instance, I want the a, b, and c fields for the new Y instance to be populated with the values from the X instance.

Obviously these fields would not be pre-populated if I just go to "add new Y" in the admin!

I have searched quite a bit to no avail!

Anyone had any success?

(I'm using django 1.3 with Python 2.6; I don't think any code snippets are required here.)

回答1:

Sorry, may be a bit too late but I think this is the answer

Django support url param in admin. You can do like this

http://localhost/admin/app/model/add/?model_field=value

then you can add foreign key by replace model_field with your foreign key name and value with the ID. Hope this help someone else :D



回答2:

So you would prefer to have an additional button called "Add new Y" that inserts another row into Y with data from X?

Then override the save() method on X so it inserts a row into Y every time it gets called.