Reverse Engineering of the Django Admin Foreign Key's Add/Edit Button
Posted: 07 July 2017 | Post By: Jai Singhal | |
8 min read |
In this tutorial, we will learn about how to add Django Admin’s Foreign key’s Add and Edit feature on Django form, so that we can easily add and edit the Foreign Key element in a pop-up window without refreshing the same page. This can be done with the help of AJAX.
Recently I was working on a project and I wanted a functionality such that I can add Foreign Key element just like Django Admin provides. I wanted this feature to be implemented in a form of my app and I found this interesting and surely it will be interesting and helpful to you too.
Now let’s implement this functionality to your Django app. I will discuss the implementation with the help of an example. Here I take an example of Model Book and Author where Author is a foreign key field in Book Model.
For the example discussed above, the class Model Author and Book would look like which is shown below. You need NOT to change your models.py, this is just for the sake of explaining with the appropriate example.
Design your form and do other Validations, here I am, showed you a basic example of forms
Now, this is the important part of this tutorial. First of all, import all the forms, models and all the necessary imports to the view. Here I am using Function based views, you can use Class Based views it doesn’t matter.
These functions are self-explanatory, only the HttpResponse with JS script may be tricky for you to understand, it is only sending a response of script to close the popup by calling the function closePopup once the form is successfully submitted.
Note that in function get_author_id(), I have used a decorator @csrf_exempt, this is done so because when you make Ajax call you need to send csrftoken in data. You can remove this decorator and send a csrftoken with the ajax call which is discussed the same in the previous Post
Configure your URLs according to your views
Create the main form for the Book(for this example).
Note that I have taken images from the Admin icon images for add and edit.
Add the following Jquery Script to either above form or to the base.html
Create an Ajax Call that will activate when edit link is clicked. This Ajax Call is made to get the ID of the name which it is associated.
Create a basic form for the foreign key Model i.e., Author in this example.
If you have followed the same example, you will get this type of output.
If you have any Question regarding the above tutorial feel free to comment below. And also share the experience with the DjangoPy in the comments below.