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

Comments

23 responses to “Creating Models in Django”

  1. Your code of destiny Avatar

    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!

  2. 21kwd Avatar
    21kwd

    buy amoxicillin for sale – comba moxi amoxicillin over the counter

  3. 3z1ov Avatar

    buy diflucan 200mg for sale – buy diflucan 200mg pill buy fluconazole paypal

  4. bv9te Avatar

    buy cenforce for sale – cenforce cost order generic cenforce 50mg

  5. 91gje Avatar

    cialis online without pres – tadalafil citrate powder best price for tadalafil

  6. 5putj Avatar

    cialis blood pressure – india pharmacy cialis cialis canadian pharmacy ezzz

  7. gqcql Avatar

    order cheap viagra online uk – https://strongvpls.com/ order generic viagra canada

  8. ConnieAcags Avatar

    More text pieces like this would create the интернет better. lasix efectos secundarios

  9. 4k3xe Avatar

    More posts like this would persuade the online elbow-room more useful. https://buyfastonl.com/isotretinoin.html

  10. ConnieAcags Avatar

    This is the stripe of content I take advantage of reading. https://ursxdol.com/levitra-vardenafil-online/

  11. 2xqxh Avatar

    Thanks towards putting this up. It’s well done. https://prohnrg.com/

  12. 07weq Avatar

    More text pieces like this would insinuate the интернет better. https://aranitidine.com/fr/cialis-super-active/

  13. ConnieAcags Avatar

    This is the gentle of writing I truly appreciate.
    https://proisotrepl.com/product/clopidogrel/

  14. ConnieAcags Avatar

    pill forxiga – https://janozin.com/# forxiga brand

  15. ConnieAcags Avatar

    purchase orlistat sale – https://asacostat.com/ order xenical 60mg generic

  16. ConnieAcags Avatar

    More articles like this would pretence of the blogosphere richer. http://bbs.51pinzhi.cn/home.php?mod=space&uid=7113412

  17. Binance Avatar

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good.

  18. Rqpobam Avatar

    You can protect yourself and your ancestors by being wary when buying prescription online. Some druggist’s websites operate legally and offer convenience, reclusion, sell for savings and safeguards to purchasing medicines. buy in TerbinaPharmacy https://terbinafines.com/product/zetia.html zetia

  19. 1hwiv Avatar

    This is a keynote which is forthcoming to my callousness… Many thanks! Faithfully where can I notice the phone details in the course of questions? online

  20. big bass splash slots Avatar

    Thanks on sharing. It’s acme quality.

  21. binance create account Avatar

    Your point of view caught my eye and was very interesting. Thanks. I have a question for you.

Leave a Reply

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