Insert data into database in Django

We will be inserting data into database using the django forms.

To insert data, using forms, in django, first create a file with the name "forms.py" and create a class with the name of your model/table and add "Form" at the end of the classname as shown below. 

Inside the class "Meta", specify the model name and the fields you want to insert the data. You can either use the '__all__' , which means you want to interact with all the fields in that model as shown below:

from django.forms import ModelForm
from .models import Student

class StudentForm(ModelForm):
    class Meta:
        model = Student
        fields = '__all__'
You can mention the fields you want to insert the data one by one as shown below :

class StudentForm(ModelForm):
    class Meta:
        model = Student
        fields = ['name','email','phone','course']

We have successfully created the form for the database interactions. To perform the CRUD operations, first we have to create a url. Open the urls.py file inside the application folder. (accounts/urls.py in our example. If you don't find a urls.py file in your application folder, refer this article's Step-1)

Create a new path in the urlpatterns list as shown below 

urlpatterns = [
    path('add-student/', views.addStudent, name="add-stud"),
]

Open the views.py file and create a function with the name addStudent as given in the path above. 

from .models import *
from django.shortcuts import render, redirect
from .forms import StudentForm
# Create your views here.

def addStudent(request):
    form = StudentForm
    context = {'form':form}
    return render(request, 'accounts/add-student.html', context)

Inside the addStudent() function, we have created a variable "form" and assigned it with the StudentForm which we created in the forms.py and we have imported the StudentForm above.

Now to view the form in the browser, we have to render a html file and pass the StudentForm in the render(). So create a html file inside the app/templates/app/ directory(If you are following the series, refer this page to understand how to create that path). In our example : accounts/templates/accounts/

Create the file with the name "add-student.html" as we have mentioned in the addStudent's render() function.

Open the add-student.html file and just print the "form" variable as shown below:

{% extends 'accounts/layouts/maintemp.html' %}

{% block title %}
Add Student
{% endblock title %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Add Student </h1>
            <form action="" method='POST'>
                {% csrf_token %}
                {{form.as_p}}
                <button type="submit" class="btn btn-primary btn-sm" value=""> Save</button>
            </form>
        </div>
    </div>
</div>

{% endblock content %}

(If you don't understand the {% block %} and {% endblock %} concept, refer this page to understand templating and extending templates.)

Here, inside the <form> tag, add the action=" " and method="POST". We will leave the "action" attribute empty now. You will understand, why we have left it empty, in the below paragraph. We will handle the post request in the views.py.

Always remember the following points when trying to post data:

  • Add a <button> inside the form tag and add type="submit" inside the button tag.
  • Whenever you use the <form> tag, always add the csrf_token. csrf_token is used to ensure that the POST request is originated from a verified domain.
  • Whenever trying to insert the data, always mention the method="POST".

We have printed the variable form using the {{ }}. We can directly write it as {{form}} and you will be able to view the form on as the output but all the input tags will be attached to each other in one row. So we used {{form.as_p}}, this will add a <p> tag to each input tag in the form and beautify the form.

Now we have to write the code to save the data which we will be sending through the form.

As we had left the (<form action=" ">) action empty, it will go to the same url on which it is loaded (add-student), and in that path we have given the function "views.addStudent". So it will go to the same function in the views.py where we had written the code to view the form. Open the views.py file and add the below code inside the addStudent function.

def addStudent(request):
    form = StudentForm
    
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save()
            #redirect('home') //redirect to any page you wish to send the user after registration 
    context = {'form':form}
    return render(request, 'accounts/add-student.html', context)

Here, we have given an if condition in which we are checking if the method is POST. If it the condition satisfies, We are assigning the form with the StudentForm along with the form data we have sent from the add student form. Then we are checking if the form is valid using the is_valid() and then we have saved the form and it will automatically return to the template we have mentioned below.

Now your form data in successfully inserted in the database. You can check it in the admin panel under the Students heading. Once you open the Students table, you will be able to see the student's name in the list of student. It will actually display as student object(1) and so on. To view the name, we had written the code in the models.py in the Student model.

Tags: Funda of web it Django tutorials, Django tutorials, Django tutorials funda, django for beginners, how to insert data into database in djangom django 3 tutorials, how to make a CRUD application in django,