Update data into Databasee
How to update data into database in django?
First, we have fetch the data and view it in our index.html. Add a edit button and give the href as shown in the below example:
let us create a new url in the urls.py to perform the update operation. Open your urls.py file and paste the below code:
Here, we have mentioned that along with the edit request, we will be sending an id for which we have to edit the data. You can see how to write the url. In this above url, <str:pk> means we will be sending a string value, and we have named it pk here. This pk we will have to pass as a parameter in the editStudent() function in the views.py as shown below:
Open your views.py file and create the function editStudent().
We have first fetched the student data and stored it in the student_id variable and then we have called the StudentForm and passed the student_id in the StudentForm and stored it in the form variable. So when we first click on the edit button, it will just fetch the data of that particular id and it will show the edit-student.html along with the data of that student.
Once you have entered the updated data in the textbox, click on the update button. As we had already studied in the insert data into data we have to mention method="POST" in the form tag whenever inserting or updating data, It will come to the editStudent() and this time the request will be of POST method so it will go inside the if condition and check if the form is valid and save the data. After the form is saved, it will redirect to the path with the name ''students'. These are the urls we will be having in the urls.py file.
In the edit-student.html, we have to print the form inside a form tag along with a button as shown below:
Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, how to update data in database in django, django tutrorials, django crud application, update data in django, django 3