Creating Models in Django

🚀 Creating Models in Django

Django models define the structure of your database tables. Each model is a Python class that inherits from models.Model, and Django automatically creates database tables based on these models.


1️⃣ Step 1: Create a Django App (If Not Already Created)

First, make sure you are inside your Django project directory and create an app:

python manage.py startapp myapp

Then, add the app to INSTALLED_APPS in settings.py:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'myapp',  # Add your app here
]

2️⃣ Step 2: Define Models in models.py

Open myapp/models.py and define your models. Here’s an example:

from django.db import models
from django.utils import timezone

class UserProfile(models.Model):
    GENDER_CHOICES = [
        ('M', 'Male'),
        ('F', 'Female'),
        ('O', 'Other'),
    ]

    name = models.CharField(max_length=100)  # Text field with a max length
    email = models.EmailField(unique=True)  # Unique email field
    age = models.IntegerField()  # Integer field for age
    profile_picture = models.ImageField(upload_to='profile_pics/', blank=True, null=True)  # Image upload
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)  # Dropdown choices
    date_joined = models.DateTimeField(default=timezone.now)  # Auto date field

    def __str__(self):
        return self.name  # String representation for admin panel

3️⃣ Step 3: Run Migrations

Django uses migrations to create the corresponding database tables.

Run these commands:

python manage.py makemigrations myapp
python manage.py migrate
  • makemigrations → Converts model changes into migration files.
  • migrate → Applies those migrations to the database.

4️⃣ Step 4: Register Models in Admin Panel (Optional)

To make your models visible in the Django Admin Panel, edit myapp/admin.py:

from django.contrib import admin
from .models import UserProfile

admin.site.register(UserProfile)  # Registers the model in the admin panel

Now, create a superuser to access the admin panel:

python manage.py createsuperuser

Then, log in at http://127.0.0.1:8000/admin/.


5️⃣ Step 5: Using Models in Django Views

You can now fetch data from your models in views.py:

from django.shortcuts import render
from .models import UserProfile

def user_list(request):
    users = UserProfile.objects.all()  # Get all user profiles
    return render(request, 'user_list.html', {'users': users})

🎯 Summary

Create an appstartapp myapp
Define models in models.py
Run migrationsmakemigrations & migrate
Register models in admin.py
Use models in views and templates

11 thoughts on “Creating Models in Django

  1. I’m really inspired along with your writing abilities and also with the format on your blog. Is that this a paid topic or did you modify it your self? Anyway stay up the nice high quality writing, it’s uncommon to peer a great blog like this one these days!

Leave a Reply

Your email address will not be published. Required fields are marked *