DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

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.


READ complete article on this link

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
Enter fullscreen mode Exit fullscreen mode

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
]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

Now, create a superuser to access the admin panel:

python manage.py createsuperuser
Enter fullscreen mode Exit fullscreen mode

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})
Enter fullscreen mode Exit fullscreen mode

🎯 Summary

βœ… Create an app β†’ startapp myapp

βœ… Define models in models.py

βœ… Run migrations β†’ makemigrations & migrate

βœ… Register models in admin.py

βœ… Use models in views and templates

Top comments (0)