Skip to content
PotatoScript edited this page Mar 2, 2025 · 17 revisions

🚀 Django Framework – Full Step-by-Step Guide 🎯

Django is a high-level Python web framework that lets you build powerful and scalable web applications quickly. It follows the Model-View-Template (MVT) architecture and includes built-in tools for authentication, database management, and security.


📌 1. Installing Django

To install Django, ensure Python and pip are installed.

✅ Step 1: Check Python & pip Versions

Open a terminal and type:

python --version
pip --version

✔ If Python 3.x is installed, you're ready to proceed.

✅ Step 2: Install Django

Run:

pip install django

✔ This installs the latest Django version.

✅ Step 3: Verify Django Installation

django-admin --version

✔ If you see a version number, Django is installed successfully! 🎉


📌 2. Creating a Django Project

A Django project is a collection of settings and configurations for a web application.

✅ Step 1: Create a New Project

django-admin startproject myproject

✔ This creates a myproject folder with Django settings.

✅ Step 2: Navigate to the Project Folder

cd myproject

✅ Step 3: Run the Development Server

python manage.py runserver

✔ Open http://127.0.0.1:8000/ in your browser.
✔ If you see "Congratulations! It worked!", Django is running! 🎯


📌 3. Django Project Structure

After running startproject, Django creates these files:

myproject/
│── manage.py         # Command-line tool for Django
│── myproject/        # Main project directory
│   │── settings.py   # Configuration file
│   │── urls.py       # URL routing
│   │── wsgi.py       # Web server gateway
│   │── asgi.py       # ASGI server file

📌 4. Creating a Django App

A Django app is a modular component of a project.

✅ Step 1: Create an App

python manage.py startapp myapp

✔ This creates a folder myapp/ for the app.

✅ Step 2: Add the App to Django Settings

Open settings.py and add "myapp" inside INSTALLED_APPS:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'myapp',  # Add your app here
]

📌 5. Creating a View

A view handles requests and returns a response.

✅ Step 1: Define a View

Open myapp/views.py and add:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, Django!")

✅ Step 2: Configure URL Routing

Open myapp/urls.py and add:

from django.urls import path
from .views import home

urlpatterns = [
    path('', home),
]

✔ If urls.py doesn’t exist in myapp/, create it manually.

✅ Step 3: Link the App’s URL to the Project’s URL

Open myproject/urls.py and modify:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('myapp.urls')),  # Include myapp URLs
]

✅ Step 4: Restart Server & Test

python manage.py runserver

✔ Open http://127.0.0.1:8000/ → You should see "Hello, Django!"


📌 6. Django Templates (HTML Frontend)

Django uses templates to separate logic from presentation.

✅ Step 1: Create a Templates Folder

Inside myapp/, create a folder:

myapp/
│── templates/
│   │── home.html  # HTML file

✅ Step 2: Create an HTML File (home.html)

<!DOCTYPE html>
<html>
<head>
    <title>My Django Page</title>
</head>
<body>
    <h1>Welcome to Django!</h1>
</body>
</html>

✅ Step 3: Modify views.py to Render the Template

from django.shortcuts import render

def home(request):
    return render(request, "home.html")

✔ Refresh http://127.0.0.1:8000/ → You should see the HTML page! 🎯


📌 7. Django Models (Database Handling)

Django models define database structure.

✅ Step 1: Create a Model in models.py

from django.db import models

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

✅ Step 2: Apply Migrations

python manage.py makemigrations
python manage.py migrate

✔ This creates a database table for Product.


📌 8. Django Admin Panel

Django provides a built-in admin panel.

✅ Step 1: Create a Superuser

python manage.py createsuperuser

✔ Enter username, email, and password.

✅ Step 2: Register the Model in admin.py

from django.contrib import admin
from .models import Product

admin.site.register(Product)

✅ Step 3: Start the Server & Access Admin Panel

python manage.py runserver

✔ Go to http://127.0.0.1:8000/admin/
✔ Log in and manage database entries!


📌 9. Django Forms (Handling User Input)

Django has forms to handle user input.

✅ Step 1: Create a Form in forms.py

from django import forms
from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = ['name', 'price']

✅ Step 2: Use Form in views.py

from django.shortcuts import render
from .forms import ProductForm

def add_product(request):
    if request.method == "POST":
        form = ProductForm(request.POST)
        if form.is_valid():
            form.save()
    else:
        form = ProductForm()
    
    return render(request, "add_product.html", {"form": form})

✅ Step 3: Create add_product.html

<form method="POST">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Add Product</button>
</form>

✔ Now, users can submit a product form!


📌 10. Django REST Framework (API Development)

To build REST APIs, install Django REST Framework:

pip install djangorestframework

✅ Step 1: Add to settings.py

INSTALLED_APPS = [
    'rest_framework',
    'myapp',
]

✅ Step 2: Create an API View in views.py

from rest_framework.response import Response
from rest_framework.decorators import api_view

@api_view(['GET'])
def api_home(request):
    return Response({"message": "Hello, API!"})

✅ Step 3: Define API URL

from django.urls import path
from .views import api_home

urlpatterns = [
    path('api/', api_home),
]

✔ Visit http://127.0.0.1:8000/api/ → You’ll see {"message": "Hello, API!"}


Tip: to enlarge your pyCharm editor

In the Settings/Preferences dialog ( Ctrl+Alt+S ), 
go to Editor | General (Mouse Control section). 
Select the Change font size with Ctrl+Mouse Wheel in option. 
Return to the editor, press and hold Ctrl , 
and using the mouse wheel, adjust the font size.

home

https://www.codingforentrepreneurs.com/guides/install-python-on-windows/

Installing django pip install django==2.1.5
Create Virtual environment python -m venv myenvname
■ Create django project django-admin startproject yourProjectName . where the period tell that your project was in current folder
■ Run project python manage.py runserver where manage.py is the module to manage django project
Create app in your project use multiple apps to control your project
Create your View
URL Mapping
Model
Migrations you can reset the database by deleting all the files in the migration and the
Admin register your app model in the admin.py
Python Shell Use python shell to register product
Templates {% block content%}{% endblock %} https://docs.djangoproject.com/en/4.0/ref/templates/builtins/
Form Create Product.objects.get(id=1) Create DB data
Raw HTML Form create your own input field without {{ form.as_p }}
Better way to insert data create a better insert data form
Form Widgets
Form Validation
Class Based Views ListView
Connect with PostgreSQL pip install psycopg2

home

Installing

  • open your project terminal in the pyCharm and type pip install django==2.1.5 where 2.1 is the version number
  • If you are in Windows and the error mentions something like: ... Connection aborted.', PermissionError ... Make sure you open the CMD with "Run as Administrator"

home

Create-Virtual-Environment

  • type pwd to see your location\
  • to create virtual env type python -m venv potatoscript - potatoscript is your env name
  • to activate the virtual env type .\potatoscript\Scripts\activate
  • Deactivate and reactivate To deactivate, just type: (potatoscript) deactivate To reactivate type: .\potatoscript\Scripts\activate

home

Create-App

  • each app is actually the python's package
  • type python manage.py startapp appname
  • python will create a package folder called appname for you and you can reuse it in your project or you can public it in the pip api for other people to use it
  • your will have a file called admin.py it is your login logout panel administrator CRUD
  • apps.py is your project configuration file

home

Create-View

  • open our views.py module
  • create a function with the http request parameter as below
      from django.http import HttpResponse
      from django.shortcuts import render
    
      def index(request):
      return HttpResponse('Hello World')

home

URL-Mapping

  • to tell dJango that when user call /products -> index we need to Map the URL(Uniform Resource Locator -> Address)
  • go to our project app and create a python file called urls you must name it urls as requested by django
    from django.urls import path
    from . import views
    # '' mean the root path
    urlpatterns = [
       path('', views.index)
    ]
- Next we need to tell django where is our app
  - go to our project folder and select `urls.py` and type the following
  - we need to add `include` in the `from django.urls import path`
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('products/', include('products.urls'))
]
  • to navigate to new path products\new create a new function in the views and add its path in the app's urls
def new(request):
    return HttpResponse('New Page')
urlpatterns = [
    path('', views.index),
    path('new', views.new)
]
  • another way of mapping the url is just using one urls.py file as below
from django.contrib import admin
from django.urls import path
from products.views import index, new, about

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name = 'index'),
    path('new/', new),
    path('about/', about),
]
  • the following is not a good practice
from django.contrib import admin
from django.urls import path

from pages import views

urlpatterns = [
    path('', views.home_view, name='home'),
    path('admin/', admin.site.urls),
]
  • you should change the above to the following
from django.contrib import admin
from django.urls import path

from pages.views import home_views, contact_view

urlpatterns = [
    path('', home_view, name='home'),
    path('contact/', contact_view, name='contact'),
    path('admin/', admin.site.urls),
]

home

Model

  • in the app models.py create a new class called Product
  • we need to inherit all the models module into the class
  • this models.Model contain all the behavior we want to CRUD it to database
from django.db import models

class Product(models.Model):
    name = models.CharField(max_length=255) #to prevent hacker to input something strange
    price = models.FloatField()
    stock = models.IntegerField()
    image = models.CharField(max_length=2083) #2083 is the max standard length in the input field

class Product2(models.Model):
    title       = models.CharField(max_length=120)
    description = models.TextField(blank=True, null=True)
    price       = models.DecimalField(decimal_places=2, max_degits=10000)
    summary     = models.TextField(default='this is cool') #summary     = models.TextField(blank=True, null=False)
    featured    = models.BooleanField() # null=True, default= True
  • after you add some data into the database without the featured field and you try to run the makemigrations it will give you error

image select 1 and then type True

home

Migrations

  • Use the models to create database table to storing product
  • go to browser and search for db browser for sqlite https://sqlitebrowser.org/ install the sqlite into our machine
  • and drag and drop our database file db.sqlite3 from our pyCharm
  • next go to our project folder and open setting.py and look for INSTALLED_APPS and include our ProductsCongfig path into it. To let django know where is our app
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'products.apps.ProductsConfig'
]
  • to auto create the table with the column fields as in our model type the following in the terminal python manage.py makemigrations
  • to generate our db table run the following in the terminal django will look for the pending migration python manage.py migrate

home

Admin

  • django by default come with the administration panel
  • let create a super user -> in the terminal python manage.py createsuperuser
  • it can let you manage your user just one line code as above and it also can let you manage your products
    • open the admin.py and type the following -> it tell django to register our Product into the admin
from django.contrib import admin
from .models import Product

admin.site.register(Product)

image

home

Python-Shell

  • at the root of your project type python manage.py shell
  • at the shell type >>>from products.models import Product
  • >>>Product.objects.all() to list out the queryset which is default in the django command
  • to create new item in the products type >>>Product.objects.create(title='New product 2', description='anotther one', price='200', summary='anything you like ')

home

Templates

  • Create a folder called Templates and register it in the Settings.py
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        ...
    },
]
  • Create a base.html as Templates inheritance
...
    <body>
        {% block content %}
        share content
        {% endblock%}
        <p style="color:blue;font-size:12px">copyright by LIM 2022</p>
    </body>
...
  • Create the views page like home.html, contact.html, about.html and extend them to base.html
{% extends 'base.html' %}
{% block content %}
<h1>This is homepage</h1>
{% endblock %}
  • setting in the urls.py
from django.contrib import admin
from django.urls import path

from pages.views import home_view, contact_view, about_view

urlpatterns = [
    path('', home_view, name='home_view'),
    path('contact/', contact_view),
    path('about/', about_view),
    path('admin/', admin.site.urls),
]
  • Next we can include other template into our current template by using {% include 'navbar.html' %}
    <body>
        {% include 'navbar.html' %}
        {% block content %}
        share content
        {% endblock%}
        <p style="color:blue;font-size:12px">copyright by LIM 2022</p>
    </body>
  • for loop in the template tag
{% extends 'base.html' %}

{% block content %}
<h1>This is Contact</h1>
<p>
    {{ my_text }}, my number is {{ my_number }}
</p>
<ul>
    {% for item in my_list %}
      {% if item == 321 %}
        <li>{{ forloop.counter }} - {{ item|add:1000 }}</li>
      {% elif item == "abc" %}
        <li>This is not a network</li>
      {% else %}
        <li>{{ forloop.counter }} - {{ item }}</li>
      {% endif %}
    {% endfor %}
</ul>
{% endblock %}

Form-Create

home

  • views.py in products
from django.shortcuts import render
from .models import Product

def product_detail_view(request):
    obj = Product.objects.get(id=1)
    #context = {
    #    "title": obj.title,
    #    "description": obj.description
    #}
    context = {
        'obj': obj
    }
    return render(request, "product/detail.html", context)
  • Form Create DB Step 1: create form.py
from django import forms

from .models import Product

class ProductForm(forms.ModelForm):
    class Meta:
        model = Product
        fields = [
            'title',
            'description',
            'price'
        ]
  • Form Create DB Step 2: create view by adding the following in the views.py
from django.shortcuts import render

from .forms import ProductForm

from .models import Product


def product_create_view(request):
    form = ProductForm(request.POST or None)
    if form.is_valid():
        form.save()
        form = ProductForm() # this is to clear the input fields value after save
    context = {
        'form': form
    }
    return render(request, "products/product_create.html", context)
  • Form Create DB Step 3: create product_create.html inside the in app templates
{% extends "base.html" %}

{% block content %}
<form method="POST"> {% csrf_token %} # the csrf_token was for security of POST
    {{ form.as_p }} # this will generate the input fields base on the model for you automatically
    <input type='submit' value="Save" />
</form>
{% endblock %}
  • Form Create DB Step 4: add to urls.py
from products.views import product_detail_view, product_create_view

urlpatterns = [
    path('', home_view, name='home_view'),
    path('contact/', contact_view),
    path('about/', about_view),
    path('create/', product_create_view),
    path('product/', product_detail_view),
    path('admin/', admin.site.urls),
]

Raw-HTML-Form

home

  • product_create.html
{% extends "base.html" %}

{% block content %}
<form action='.' method="POST"> {% csrf_token %}
    <!--{{ form.as_p }}-->
    <input type="text" name="title" placeholder="your title" />
    <input type='submit' value="Save" />
</form>
{% endblock %}
  • views.py
def product_create_view(request):
    #print(request.GET)
    #print(request.POST)
    if request.method == "POST":
        my_new_title = request.POST.get('title')
        print(my_new_title)
        # Product.objects.create(title=my_new_title)
    context = {}
    return render(request, "products/product_create.html", context)

Better-Create

home

  • views.py
def product_create_view(request):
    form = RawProductForm() # to initial the form look like 
    if request.method == "POST":
        form = RawProductForm(request.POST) # use request.POST to do some action
        if form.is_valid():
            #now the data is good
            #print(form.cleaned_data) #cleaned_data is the data come from the form after you submit it
            Product.objects.create(**form.cleaned_data) #we need to use ** to pass the data as argument
            form = RawProductForm()
        else:
            print(form.errors)
    context = {
        "form" : form
    }
    return render(request, "products/product_create.html", context)
  • product_create.html
{% extends "base.html" %}

{% block content %}
<form action='.' method="POST"> {% csrf_token %}
    <!--{{ form.as_p }}-->
    <!--<input type="text" name="title" placeholder="your title" />-->
    {{ form.as_p }} <!--you can change the display style to as_ul or as_p or ...-->
    <input type='submit' value="Save" />
</form>
{% endblock %}

Form-Widgets

home

  • use the form widget you can overwrite the thing in the form
class RawProductForm(forms.Form):
    title       = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder":"my title"}))
    description = forms.CharField(
                        required=False, 
                        widget=forms.Textarea(
                            attrs={
                                "class": "new-class-name two",
                                "rows": 20,
                                "cols": 90,
                                "id": "my_textarea_id"
                            }
                        ))
    price       = forms.DecimalField(initial=200)

Form-Validation

home

class ProductForm(forms.ModelForm):
    title       = forms.CharField(label='', widget=forms.TextInput(attrs={"placeholder":"my title"}))
    email       = forms.EmailField()
    description = forms.CharField(
                        required=False, 
                        widget=forms.Textarea(
                            attrs={
                                "placeholder": "Your description",
                                "class": "new-class-name two",
                                "rows": 20,
                                "cols": 90,
                                "id": "my_textarea_id"
                            }
                        ))
    price       = forms.DecimalField(initial=200)

    class Meta:
        model = Product
        fields = [
            'title',
            'description',
            'price'
        ]
    
    def clean_title(self, *args, **kwargs):
        title = self.cleaned_data.get("title")
        if not "CFE" in title:
            raise forms.ValidationError("This is not a valid title")
        if not "news" in title:
            raise forms.ValidationError("This is not a valid title")    
        else:
            return title

    def clean_email(self, *args, **kwargs):
        email = self.cleaned_data.get("email")
        if not email.endswith("edu"):
            raise forms.ValidationError("This is not a valid email")  
        else:
            return email    

Class-Based-Views

home

  • views.py
from django.shortcuts import render

from django.views.generic import(
    CreateView,
    DetailView,
    ListView,
    UpdateView,
    DeleteView
)

from .models import Article

class ArticleListView(ListView):
    template_name = 'articles/article_list.html'
    queryset = Article.objects.all() # <blog>/<modelname>_list.html
  • in app url.py
from django.urls import path
from .views import(
    ArticleListView
)

app_name = 'articles'
urlpatterns = [
    path('', ArticleListView.as_view(), name='article-list')
]

Connect-PostgreSQL

home

  1. install djangorestframework pip install djangorestframework
  2. install psycopg2 pip install psycopg2

Clone this wiki locally