How to Update Data in Database Using Django

In an earlier tutorial, we have learned to create your first Django application. In this tutorial, we are going to learn about creating Django form and store data into the database.

The form is a graphical entity on the website where the user can submit their information. Later, this information can be saved in the database and can be used to perform some other logical operation.

As a part of this tutorial, we are going to create one HTML form where the user can enter their data. We will save this data into the Django's default SQLite database.

Create an HTML form and Insert Data into the Database using Django

There are multiple steps involved. Let's start one-by-one.

Step 1. Creating a Model Class

Model is nothing but the source of information about the data where we can define the type of data, behavior.

Usually, one model class maps to one database table.

You can found all the defined models in models.py file.

Open models.py and write model class in it.

from django.db import models  class MyModel(models.Model):     fullname = models.CharField(max_length=200)     mobile_number = models.IntegerField()          

Explanation:

  • In the first line of the code, we are importing models.
  • Create a new form (says MyForm) that is inherited from the models.Model class.
  • One-by-on you can define the form data/field with their data types.

In the above example, we have created two model data fields – CharField() and IntegerField().

Step 2. Understanding Different Model Field Types

There are different model field types you can use in the Django models. Most of these field types are self-descriptive.

Let's check them one-by-one.

Field Name Description
AutoField It is an IntegerField that automatically increments for each entry.
BigAutoField It can store values up to a 64-bit integer. This is also an automatically incremented field with a higher range of values.
BigIntegerField It is similar to the IntegerField except that it is can store more values (up to 64-bit).
BinaryField It is used to store binary data (zeros and ones).
BooleanField It is a boolean field to store true or false.
By default, the checkbox form widget can be used.
CharField It is used to store the set of characters (string). You can limit the number of characters.
DateField Basically it is datetime.date instance. It can be used to store the date.
DateTimeField It is used for date and time, represented in Python. It is a datetime.datetime instance.
DecimalField You can save a fixed-precision decimal number, represented in Python. It is a Decimal instance.
DurationField This field is used for storing periods of time (time span between two timestamps).
EmailField It is an extension of CharField. It checks and stores only is a valid email address string. It throws an error if you try to store an invalid email address.
FileField This field is used to upload the file.
FloatField It is a floating-point number represented in Python by a float instance.
ImageField It is an advance version of FileUpload and inherits all attributes and methods from FileField. Apart from this, it also checks whether the uploaded object is a valid image or not. It only accepts a valid image.
IntegerField As name resonates, it is an integer field. It can accept the values in a range of -2147483648 to 2147483647 (up to 32 bits).
GenericIPAddressField This field accepts both the IPv4 or IPv6 address. It is actually a string that is a valid IP address. (difference between IPv4 and IPv6 address)
NullBooleanField It is similar to the BooleanField. But, it also accepts NULL along with boolean values (True and False).
PositiveIntegerField This field accepts positive integer values. (Note: It also accepts zero (0).
PositiveSmallIntegerField This field accepts positive values (including zero (0)) in a certain range. The range of acceptance values depends on the database you are using.
SlugField Slug is a special string. which contains only letters, numbers, underscores, and hyphens. It is a short label. One of the examples of the slug is URL.
SmallIntegerField It is similar to the PositiveSmallIntegerField as we have seen. But, it accepts both positive and negative values including zero (0).
TextField This field is used to store a large text. For creating a form, we can use Textarea as a default form widget for TextField.
TimeField It is a time field. It does not care about the date. In Python, it is an instance of datetime.time.
URLField If you want to store URL in the database, use this URL. The value in this field is validated by URLValidator.
UUIDField UUID is a universally unique identifier. This field accepts the UUID string.

Relationship Fields:

Django also defines a set of fields that represent relations between two data fields.

If you know the database, it has various keys used to map the relation. Similarly we can define those relations using relationship fields in Django.

Field Name Description
ForeignKey The foreign key represents many-to-one relationships. With the Foreign key, we can derive the key from the primary key of another model. For using ForeignKey two positional arguments are required- the class from where the key is derived and on_delete option (what should be the behavior if the primary key is deleted).
ManyToManyField It maintains a many-to-many relationship. This field also requires positional arguments just like Foreignkey field, including recursive and lazy relationships.
OneToOneField It creates the one-to-one mapping between two model data.

Step 3. Making Migrations and Setting Database

After writing Django model, you need to create the migrations. Run following command to create the migrations.

python manage.py makemigrations

After running the command, you can see the migrations file created under the migrations folder. Something like this 0001_initial.py.

You are done with creating migrations. To reflect thing migrations into the database, you have to run below command.

python manage.py migrate

You have applied migrations to the database successfully.

With this, you are have created backend.

Let's create the front-end (form) to take the data from user.

Step 4. Create Form to Take the User Input

Instead of creating HTML form manually, Django has its easy way of doing it.

First of all, create new file as forms.py and write below Python code.

We are defining the form and attributes to display in the form.

from django import forms from .models import MyModel  class MyForm(forms.ModelForm):   class Meta:     model = MyModel     fields = ["fullname", "mobile_number",]     labels = {'fullname': "Name", "mobile_number": "Mobile Number",}          

Here are the things we are doing.

  • Inheriting forms.ModelForm class to create our own form.
  • In Meta class, we are defining the form attributes.
  • With the labels, we can customize form field labels to display.

Now create HTML page template to display Django form.

<div class="container">     <form method="POST">       <fieldset>         <legend>Form</legend>         {% csrf_token %}         {{ form.as_p }}         <button type="submit" class="btn btn-primary">Submit</button>       </fieldset>     </form> </div>          

Let's save the file as cv-form.html in templates directory.

Even if you know the basic HTML, you can understand above HTML code.

You can also use bootstrap to customize the form and to make it look nice. I will show you that in the next tutorial. Now stick with this and continue with our tutorial to create an HTML form and insert data into the database using Django.

Let's fine new function in views.py Python file.

from django.shortcuts import render from .models import MyModel from .forms import MyForm  def my_form(request):   if request.method == "POST":     form = MyForm(request.POST)     if form.is_valid():       form.save()   else:       form = MyForm()   return render(request, 'cv-form.html', {'form': form})          

This function will be called when user hit the form URL in the web browser.

Step 5. Set URL and Run Django Application

Let's call this form function by mapping it to the URL. Go to the urls.py and add below line of code in urlpatterns list.

url(r'form', views.my_form, name='form')

Now run and start the local server to test using below command.

python manage.py runserver

It will start the local server. Now open localhost in web browser.

Whenever a request comes to http://localhost:8000/form, it will call to the my_form() function defined in views.

Wow! You have created your first form. Submit the sample data in the form. The data will be saved in the database.

You can also see all the data submitted by the user in the Django admin dashboard. You have to register the model into the Django admin site.

In this tutorial, you have learned to create an HTML form and insert data into the database using Django.

Keep Learning!

Python Interview Questions eBook

How to Update Data in Database Using Django

Source: https://www.csestack.org/create-html-form-insert-data-database-django/

0 Response to "How to Update Data in Database Using Django"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel