When learning Django, one of the most powerful things you'll discover is how effortlessly it lets you interact with databases using models. In this guide, I’ll walk you through how to write to a database in Django using real examples, no steps skipped!
Whether you're just starting or you’re working on a mini project, this article will help you:
- Set up your virtual environment
- Install Django
- Start a project and app
- Create and configure a model
- Run the server and interact with the database Step 1: Set Up Your Environment: On my previous post on python i showed the walkthrough on the creation and interacting with django, but first, create a new folder for your project, then open your terminal or command prompt inside that folder.
python -m venv venvname
cd venvname\Scripts
activate.bat
cd ../..
💡 Note: venvname can be any name for your virtual environment.
Once activated, install Django:
python -m pip install django
You should see Django and its dependencies installing without issues.
Step 2: Create Your Django Project and App
Next, use the Django CLI to set up your project and an app inside it.
django-admin startproject connectdb .
django-admin startapp dbapp
Make sure your structure looks like this
djangopractice/
├── connectdb/
├── dbapp/
├── venvname/
├── manage.py
in the root folder in your file explorer
Step 3: Create Your Model
Now open dbapp/models.py and define your model class. For this example, `I created a Contacts model:
from django.db import models
class Contacts(models.Model):
firstname = models.CharField(max_length=100)
lastname = models.CharField(max_length=100)
age = models.IntegerField()
def __str__(self):
return self.firstname`
This will let Django know you want a table in the database called Contacts, with firstname, lastname, and age fields.
Step 4: Connect to the Database Using Django Shell
you can use the django shell but i use the command prompt for this, open a new command prompt and type in one line after the other.
cd downloads\djangopractice\venvname\Scripts
activate.bat
cd ../..
python manage.py makemigrations
python manage.py migrate
python manage.py shell
Step 5: Write to the Database
Inside the shell, you can import your model and start creating records. Here's how:
# First, import the model
from dbapp.models import Contacts
# Then, create a new instance
contact = Contacts(firstname='John', lastname='Doe', age=28)
# Save it to the database
contact.save()
That’s it! 🎉 You've just written to your database.
You can verify it by retrieving all records by
Contacts.objects.all()
In my next article, I’ll show you how to:
- Register your models with the Django admin
- Create a superuser
- Use Django’s powerful built-in admin interface to manage data visually if you have any question or contribution ask in the comment i will always respond
Top comments (0)