🚀 Creating Models in Django
Django models define the structure of yourdatabase tables. Each model is aPython class that inherits frommodels.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 toINSTALLED_APPS
insettings.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 inmodels.py
Openmyapp/models.py
and define your models. Here’s an example:
fromdjango.dbimportmodelsfromdjango.utilsimporttimezoneclassUserProfile(models.Model):GENDER_CHOICES=[('M','Male'),('F','Female'),('O','Other'),]name=models.CharField(max_length=100)# Text field with a max lengthemail=models.EmailField(unique=True)# Unique email fieldage=models.IntegerField()# Integer field for ageprofile_picture=models.ImageField(upload_to='profile_pics/',blank=True,null=True)# Image uploadgender=models.CharField(max_length=1,choices=GENDER_CHOICES)# Dropdown choicesdate_joined=models.DateTimeField(default=timezone.now)# Auto date fielddef__str__(self):returnself.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 myapppython 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 theDjango Admin Panel, editmyapp/admin.py
:
fromdjango.contribimportadminfrom.modelsimportUserProfileadmin.site.register(UserProfile)# Registers the model in the admin panel
Now, create asuperuser to access the admin panel:
python manage.py createsuperuser
Then, log in athttp://127.0.0.1:8000/admin/.
5️⃣ Step 5: Using Models in Django Views
You can nowfetch data from your models inviews.py
:
fromdjango.shortcutsimportrenderfrom.modelsimportUserProfiledefuser_list(request):users=UserProfile.objects.all()# Get all user profilesreturnrender(request,'user_list.html',{'users':users})
🎯 Summary
✅Create an app →startapp myapp
✅Define models inmodels.py
✅Run migrations →makemigrations & migrate
✅Register models inadmin.py
✅Use models in views and templates
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse