top of page

Insert Data into a Django model and then show that data

  1. Create a Django model: First, define a model in your Django app to represent the data you want to store. A model is a Python class that inherits from django.db.models.Model and represents a database table.

  2. Set up the database: After defining the model, run migrations to create the corresponding table in the database.

  3. Insert data: You can insert data into the model using Django's Object-Relational Mapping (ORM) system. You'll create instances of the model and save them to the database.

  4. Show data: To display the inserted data, you can create a view in Django that fetches the data from the database and renders it in a template.

Here's a step-by-step guide to accomplishing this:

Step 1: Create a Django model Assuming you have a Django app named "myapp," create a model in your app's models.py file:
# models.pyfrom django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    email = models.EmailField()

    def __str__(self):
        return self.name
Step 2: Run migrations After creating the model, run the following command to create the corresponding database table:
python manage.py makemigrations
python manage.py migrate
Step 3: Insert data You can insert data into the model using the Django shell. Start the shell with the following command:
python manage.py shell

Then, insert data using the model's constructor and save the objects:

from myapp.models import MyModel

# Inserting data
obj1 = MyModel(name='John', age=25, email='john@example.com')
obj1.save()

obj2 = MyModel(name='Alice', age=30, email='alice@example.com')
obj2.save()
Step 4: Show data Create a view in your Django app that fetches the data from the database and renders it in a template:
# views.pyfrom django.shortcuts import render
from myapp.models import MyModel

def show_data(request):
    data = MyModel.objects.all()
    return render(request, 'show_data.html', {'data': data})
Step 5: Create a template to display the data Create a template named "show_data.html" in your app's templates directory:
<!-- show_data.html --><!DOCTYPE html><html><head><title>Show Data</title></head><body><h1>Data:</h1><ul>
        {% for obj in data %}
        <li>Name: {{ obj.name }}, Age: {{ obj.age }}, Email: {{ obj.email }}</li>
        {% endfor %}
    </ul></body></html>
Step 6: Create a URL pattern to access the view Finally, create a URL pattern to access the "show_data" view in your app's urls.py:
# urls.pyfrom django.urls import path
from . import views

urlpatterns = [
    path('show/', views.show_data, name='show_data'),
]

Now, when you visit the URL /show/ in your browser, you should see the data you inserted into the MyModel displayed on the page.

Related Posts

See All

Comments


bottom of page