Django has its own Object Relation Model (ORM) that maps a Python class with a table in a relational database. The ORM mechanism helps in performing CRUD operations in object-oriented manner. In this chapter, we shall learn about different methods of inserting a new data.
By default, Django uses a SQLite database. A model in Django is a class inherited from the “django.db.models” class.
Let us use the following Dreamreal model in “models.py” file for learning how to insert data in the mapped table −
from django.db import models
classDreamreal(models.Model):
website = models.CharField(max_length=50)
mail = models.CharField(max_length=50)
name = models.CharField(max_length=50)
phonenumber = models.IntegerField()classMeta:
db_table ="dreamreal"</code></pre>
After declaring a model, we need to perform the migrations −
Django has a useful feature with which you can invoke a Python shell inside the Django project’s environment. Use the shell command with the manage.py script −
python manage.py shell
In front of the Python prompt, import the Dreamreal model −
>>>from myapp.models import Dreamreal
We can construct an object of this class and call its save() method so that the corresponding row is added in the table
Instead of using the hard-coded values as in the above example, we would like the data to be accepted from the user. For this purpose, create an HTML form in myform.html file.
Note that the form’s action attribute is also set to the same URL mapping the addnew() function. Hence, we need to check the request.method. If it’s GET method, the blank form is rendered. If it’s POST method, the form data is parsed and used for inserting a new record.
The Model Form
Django has a ModelForm class that automatically renders a HTML form with its structure matching with the attributes of a model class.
We define a DreamRealForm class in forms.py file under the app folder that uses the Dreamreal model as the basis.
from django import forms
from.models import Dreamreal
classDreamrealForm(forms.ModelForm):classMeta:
model = Dreamreal
fields ="__all__"</code></pre>
An object of the model form is rendered on the HTML form. In case the request method is POST, the save() method of the ModelForm class automatically validates the form and saves a new record.
Leave a Reply