π 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
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 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)