Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Muhammad Atif Iqbal
Muhammad Atif Iqbal

Posted on

     

Creating Models in Django

🚀 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
Enter fullscreen modeExit fullscreen mode

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

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

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
Enter fullscreen modeExit 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 theDjango Admin Panel, editmyapp/admin.py:

fromdjango.contribimportadminfrom.modelsimportUserProfileadmin.site.register(UserProfile)# Registers the model in the admin panel
Enter fullscreen modeExit fullscreen mode

Now, create asuperuser to access the admin panel:

python manage.py createsuperuser
Enter fullscreen modeExit fullscreen mode

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

🎯 Summary

Create an appstartapp myapp

Define models inmodels.py

Run migrationsmakemigrations & migrate

Register models inadmin.py

Use models in views and templates

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

AI Engineer with a software engineering background, skilled in Python, TensorFlow, PyTorch, FastAPI, Flask, Django ReactJS, and NextJS. Expert in building scalable AI models and applications.
  • Location
    Lahore, Pakistan
  • Pronouns
    Mr
  • Joined

More fromMuhammad Atif Iqbal

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp