Django

From AI - it contain errors- I will update it on 15-10-2026 turkey`s time 10:00 A.M. 

AI - source (will work only for me): 

https://www.google.com/search?q=what+is+django+orm&gs_lcrp=EgZjaHJvbWUyCggAEEUYFhgeGDkyCggBEAAYgAQYtAcyCAgCEAAYFhgeMgoIAxAAGAoYFhgeMggIBBAAGBYYHjIICAUQABgWGB4yCAgGEAAYFhgeMggIBxAAGBYYHjIICAgQABgWGB4yCAgJEAAYFhge0gEIOTA1NGowajeoAgCwAgA&sourceid=chrome&ie=UTF-8&fbs=ABfTbFVyMZGZf1hfvX9uKjN_-G8c4u0nXx4bEIpwm1lnNH832a9BVCEiB2iPJNekNderQwLP8msUKsz-6AMxGyueJZ9cK2mNBy2II_6WvkKSZWdegvvKnEPeeArWgEP9exNATg6oybL0Q4MEKOxPxFbct-gP8X2Md15J678lTd9Mq5TzLfr9mW3FHXD8PxhMtyxB-5Ur4yf8oB5hp39N1HAMTzUKxKHHoQ&aep=10&ntc=1&sxsrf=APpeQnt-pcqSX2z0BB2A-Zl8mMMb5JhGuA%3A1791544449005&mstk=AUtExfCEuo6Fobgymp2AJKiuidHO0kDEcEaQ68QdS-rHSUs64_vLkBVMOXs_7uIR6671MtgP6YuTbaRiTuDCwaDEywN74mjVLMcCQQTtHGl7QguZ7Da-RFSafx0h99Qkle205om_PX7X0NwiBAgyQEMQ9CebZuwHxh6KtyHeaWlXlFutHhFXR5gDoFaW5cFYuSYgps_K0XQAydxqPkNadm3S_bUxaD9K-rIzPJQ0Y-7xDaD1hM9WqIDT48I-Lr_M5j1PZs1-4HvWX3oSDGCEKfj_C_CsmUbWJE1u_UtSKh3pxlHOGCvy1d1V3xi3FuLw45L4reBMd6ZFnnKjgg&aioh=3&csuir=1&cs=1&mtid=58zIatGxMrj87_UPk_zGOA&udm=50

What You Need to Install (Quick Checklist)

To get everything working, follow these steps sequentially:
[1] Install Python ──> [2] Install VS Code Extensions ──> [3] Install Django via Terminal
1. Python (On your computer)
VS Code needs Python installed on your operating system to run any Python code.
2. VS Code Extensions (Inside the VS Code Marketplace)
Open VS Code, click on the Extensions icon (the four squares on the left sidebar), and install:
  • Python (by Microsoft): Gives VS Code the power to understand and run Python code.
  • Django (by Baptiste Darthenay or similar high-rated extension): Adds syntax highlighting and code snippets specifically for Django templates and models.
3. The Django Framework (Inside your project)
Once Python and the extensions are ready, you open the terminal inside VS Code and install Django into your project using Python's package manager (pip):
bash
pip install django
Use code with caution.

Summary: Who Provides What?
ComponentWhat provides it?Do you need to download it?
Code EditorVisual Studio CodeYes (Download application)
Language SupportPython & VS Code ExtensionsYes (Download from web / VS Code marketplace)
Django ORMThe Django LibraryYes (Install via terminal using pip install django)
Once you run pip install django, the Django ORM becomes available for you to import and use inside your VS Code workspace.
How to Verify the Installation
After running the commands above, you can verify that Django is correctly installed on your machine by typing this into your terminal:
bash
django-admin --version
Use code with caution.
If it prints out a version number (like 5.2 or 6.0), Django is officially ready to go.
Step-by-Step Installation for Windows
Open VS Code, open your project folder (File > Open Folder), and open the built-in terminal (Ctrl + ` or Terminal > New Terminal).
Follow these sequential steps:
StepType this Command into the TerminalWhat it Actually Does
1. Create Environmentpython -m venv .venvCreates a hidden folder named .venv to keep your project packages isolated.
2. Activate Environment.venv\Scripts\activateActivates the environment. You will see (.venv) appear at the start of your terminal line.
3. Upgrade Pippython -m pip install --upgrade pipEnsures Windows has the latest Python package manager installed.
4. Install Djangopip install djangoDownloads and installs the Django Framework and Django ORM safely inside your environment.

Ready to test?
To make sure it worked perfectly, type this command in your active terminal:
cmd
django-admin --version
Use code with caution.
If it prints out a version number, Django is successfully installed on your PC.

Launching Django

Step 1: Create a Django Project First
If you haven't generated the starter files yet, you must do that before launching. In your VS Code terminal (with your (.venv) activated), run:
cmd
django-admin startproject myproject .
Use code with caution.
(Note: The . at the end is important—it prevents Django from nesting your files inside extra folders).

Step 2: How to Launch the Server
To start your website, type this exact command into your terminal:
cmd
python manage.py runserver
Use code with caution.
What your terminal will look like:
Once you press Enter, your VS Code terminal will output text that looks like this:
text
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).

You have 18 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

October 09, 2026 - 14:50:00
Django version 5.2, using settings 'myproject.settings'
Starting development server at http://127.0.0
Quit the server with CTRL-BREAK.
Use code with caution.
(Note: Don't worry about the red warning about "18 unapplied migrations" right now. It just means your default database tables haven't been created yet, but the server will still run fine).

Step 3: What it Looks Like in Your Browser
  1. Hold down the Ctrl key and click the link http://127.0.0 inside your terminal, or open your web browser and type localhost:8000.
  2. You will be greeted by Django's official "The install worked successfully! Congratulations!" landing page.
It looks like a clean, light-blue/gray webpage featuring:
  • A rocket ship animation taking off into space.
  • A success message confirming that your setup is working.
  • Links to the official Django documentation and tutorial resources.

How to Turn it Off
The server will run forever until you stop it. To shut down the server and get your normal terminal prompt back, go to the VS Code terminal and press:
  • Ctrl + C (or Ctrl + Break on some Windows keyboards).
Good news: Your server is actually running successfully right now! This text is not an error message blocking your website; it is just a routine startup notification and warning from Django.
You can open your web browser right now, go to http://127.0.0.1:8000/, and you should see Django's landing page.
Here is a breakdown of what that output means and how to clean it up.

Breaking Down the Messages
1. The Red Warning: "You have 18 unapplied migration(s)"
  • What it means: Django comes with built-in features that require a database, such as user login systems (auth) and admin dashboards (admin). Django is simply warning you that it has created the blueprints for these database tables, but it hasn't actually built them inside your database file yet.
  • Is it a problem? No. Your site will launch, but if you try to visit the admin panel right now, it will crash because the user tables don't exist yet.
2. The Yellow/Black Warning: "WARNING: This is a development server..."
  • What it means: Django's runserver command is designed strictly for local testing on your own computer. It is optimized to restart whenever you save code changes, but it is not optimized to handle thousands of internet users securely or quickly.
  • Is it a problem? No. You can completely ignore this while you are building your website on your computer.

What You Should Do Next
To fix the "18 unapplied migrations" and set up your initial database tables, you need to run Django's database builder. Follow these steps:
Step 1: Stop the Server
Click inside your VS Code terminal and press Ctrl + C to shut down the active server.
Step 2: Apply the Migrations
Type this command into your terminal and press Enter:
cmd
python manage.py migrate
Use code with caution.
What you will see: Your terminal will scroll through a list of items and print OK next to all 18 entries. This automatically creates a local SQLite database file (usually named db.sqlite3) inside your project folder.
Step 3: Start the Server Again
Now, restart your server with:
cmd
python manage.py runserver
Use code with caution.
The red warning will be completely gone, and your console will look perfectly clean!

Create an Admin account 

so you can log in and look at your new database dashboard
To access Django's built-in database dashboard, you need to create a Superuser account. This account gives you total administrative control over your website and database.

Step 1: Create the Superuser Account
Go to your VS Code Terminal and follow these quick steps:
  1. If your development server is still running, shut it down by pressing Ctrl + C.
  2. Type this exact command and press Enter:
    cmd
    python manage.py createsuperuser
    
    Use code with caution.
  3. The terminal will guide you through a quick prompt setup. Fill out the details:
    • Username: Type a username (e.g., admin) and press Enter.
    • Email address: You can type your email, or leave it completely blank and just press Enter.
    • Password: Type a strong password and press Enter. (Note: Windows hides your text for security as you type your password. The cursor will not move, but it is registering your keystrokes!)
    • Bypass verification: If you use a simple password, it might ask you if you want to bypass the password validation. Type y and press Enter.
Once successful, you will see: Superuser created successfully.
Step 2: Log into the Dashboard
Now that your account exists, let's open up the dashboard layout:
  1. Restart your development server:
    cmd
    python manage.py runserver
    
    Use code with caution.
  2. Open your web browser and go to this exact URL:
    url
    http://127.0.0.1:8000/admin
    
    Use code with caution.
  3. You will see a dark blue and white Django Administration login portal.
  4. Type in the Username and Password you just generated in Step 1.
What It Looks Like inside Your Dashboard
Once logged in, you will be looking at Django's built-in Admin Index. It features a clean, responsive layout split into native data modules:
  • Authentication and Authorization: This section allows you to manage Groups and Users. Click on "Users" to see your own account, change passwords, or add mock users.
  • Recent Actions Panel: A sidebar tracking every change, addition, or deletion you make on the dashboard for accountability.
  • Empty Space for Custom Tables: Right now, you only see default user settings. As soon as you build custom tables (like standard products, blog posts, or orders) in your code, they will register here as clean spreadsheets where you can dynamically insert, update, or remove data rows manually.

Create your first custom database table


Let's build your first custom app and database model so it appears on your dashboard.
We will create a simple "store" app with a "Product" table.

Step 1: Create Your Custom Django App
First, stop your server in the VS Code terminal (Ctrl + C), then run this command to generate a new app folder:
cmd
python manage.py startapp store
Use code with caution.
This will create a new folder named store inside your project directory.
Step 2: Register the App in Settings
Django needs to know your new app exists.
  1. Open the file orucpy_django/settings.py.
  2. Find the INSTALLED_APPS list.
  3. Add 'store', to the top of that list like this:
python
INSTALLED_APPS = [
    'store',  # <-- Add this line
    'django.contrib.admin',
    'django.contrib.auth',
    # ... leave the rest of the list exactly as it is
]
Step 3: Define Your Model (The Table Structure)
Now let's build the layout for your table.
  1. Open store/models.py.
  2. Replace all the text inside it with this Python code:
python
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=200)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    stock = models.IntegerField()

    def __str__(self):
        return self.name  # This makes the product show its real name in the admi
Step 4: Register the Model with the Admin Panel
To make this table visible on your http://127.0.0 dashboard, you must register it.
  1. Open store/admin.py.
  2. Replace its content with this code:
python
from django.contrib import admin
from .models import Product

# This tells Django to put the Product table on the admin screen
admin.site.register(Product)
Step 5: Generate and Apply the Database Blueprint
Now we need to tell Django to create this new table in your SQLite file. Run these two commands sequentially in your terminal:
cmd
python manage.py makemigrations
Use code with caution.
(You will see a success message saying: Create model Product)
cmd
python manage.py migrate
Use code with caution.
(You will see a success message saying: Applying store.0001_initial... OK)
Step 6: Launch and Verify!
Restart your development server:
cmd
python manage.py runserver
Use code with caution.
Open your web browser and go back to http://127.0.0.1:8000/admin
You will now see a brand new section called STORE with a row labeled Products. You can click the "+ Add" button next to it to type in products, give them a price, set their stock, and save them directly into your database!
Were you able to log in and add your first product using the dashboard interface? Let me know if you run into any syntax errors along the way!

SQL Lite tables

Django’s SQLite database allows you to build any tables, columns, and data relationships exactly the way you want them to be.
However, because you are using Django ORM, you will never actually write SQL code or manipulate the SQLite file directly. Instead, you will design everything using normal Python code, and Django will handle the database creation for you.

How You Design Tables in Django (The Workflow)
Whenever you want to add a new table or modify a column, you follow a simple 3-step cycle:
[1. Design in Python] ──> [2. Generate Blueprint] ──> [3. Apply to SQLite]
     (models.py)             (makemigrations)              (migrate)


Step 1: Design your table in Python (models.py)
You define your database tables as Python classes inside your Django app's models.py file. Here is an example of what that looks like:
python
from django.db import models

class Product(models.Model):
    # This creates a text column with a 200-character limit
    name = models.CharField(max_length=200)
    
    # This creates a decimal column for currency/pricing
    price = models.DecimalField(max_digits=10, decimal_places=2)
    
    # This creates a date/time column that fills itself automatically
    created_at = models.DateTimeField(auto_now_add=True)

Step 2: Let Django generate the blueprint
Once you save your Python file, you tell Django to read your code and generate a blueprint (called a migration file) by running:
cmd
python manage.py makemigrations
Use code with caution.
Step 3: Push the blueprint to SQLite
Finally, you apply that blueprint to your SQLite database by running the command you just learned:
cmd
python manage.py migrate

Django will instantly update your db.sqlite3 file, injecting your new table (Product) along with its columns (name, price, created_at) perfectly.

SQLite Features Supported by Django ORM
Django ORM unlocks almost all modern relational database features inside SQLite:
Data FeatureDjango ORM Field TypeWhat it stores
Textmodels.TextField()Long paragraphs, blogs, descriptions.
Numbersmodels.IntegerField()Quantities, ages, scores.
True/Falsemodels.BooleanField()Statuses like is_published or is_active.
Relationshipsmodels.ForeignKey()Links two tables together (e.g., linking a Product to a Category).

Important Note for the Future
SQLite is incredible for learning, local development, and small-to-medium websites.
If your website eventually grows massive and needs to handle millions of users,
Django makes it incredibly easy to switch from SQLite to an enterprise database
like PostgreSQL or MySQL later without changing a single line of your table designs!
--------------end-------------------

Comments

Popular posts from this blog

python - pro - 22 - PYQT5 - PYQT6 - form design

python - advanced - 17 - Pandas

python-beginner - 6 - Fonksiyonlar