DJANGO

Django E-commerce Tutorial

Aşağıdakı addımlarla sıfırdan sadə Django E-commerce sistemi qura biləcəksən. Hamısı ardıcıllıqla yazılıb: terminal komandaları, modellər, view-lar və template-lər.

virtual environment & project setup models & migrations auth (signup / login) orders & products
Tip: Bu səhifəni bir növ “roadmap + kod kitabçası” kimi istifadə et. Hər addımı bitirəndə commit edib GitHub-a atsan daha yaxşı yadda qalacaq.

Əvvəlcə Django E-commerce üçün əsas strukturumuzu yaradırıq:

PowerShell — Project Setup
Django E-commerce>
0) Create empty file
1) Django E-commerce> mkdir django
2) Django E-commerce> cd .\django\
3) Django E-commerce\django> python -m venv .venv
4) Django E-commerce\django> .venv\Scripts\activate
5) Django E-commerce\django> pip install Django
6) Django E-commerce\django> django-admin startproject myproject .
7) Django E-commerce\django> python manage.py startapp accounts
8) Django E-commerce\django> python manage.py runserver
Structure is ready ✅ – Projekt və accounts app artıq hazırdır.

İlk olaraq accounts app-i INSTALLED_APPS hissəsinə əlavə edirik:

VS Code — settings.py
myproject/myproject/settings.py
Fayl:
INSTALLED_APPS = [
    ...
    'accounts',
]

1) İlk migrate
PowerShell — Initial migrate
myproject>
1) Django E-commerce\django\myproject> python manage.py migrate
2) Modelleri əlavə et

myproject/accounts/models.py faylına aşağıdakı kodu yaz:

VS Code — models.py
myproject/accounts/models.py
from django.db import models
from django.contrib.auth.models import User


class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    Name = models.CharField(max_length=50)
    Email = models.EmailField(unique=True) 


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


class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
    product = models.ManyToManyField(Product)
3) Makemigrations & migrate
PowerShell — Apply models
myproject>
2) Django E-commerce\django\myproject> python manage.py makemigrations
3) Django E-commerce\django\myproject> python manage.py migrate

Admin panelə giriş üçün superuser yaradırıq:

PowerShell — Superuser
myproject>
myproject/accounts/admin.py  (sonradan modelləri register edəcəksən)

1) Django E-commerce\django\myproject> python manage.py createsuperuser

Username (leave blank to use 'alvin'): alvin
Email address: elvinbabanli0@gmail.com
Password: 12345678 (Password going to be invisible)
Password (again): 12345678 (Password going to be invisible)
Bypass password validation and create user anyway? [y/N]: y
Superuser created successfully.

accounts.views-dən bütün view-ları import edib URL pattern-ləri yazırıq:

VS Code — urls.py
myproject/myproject/urls.py
from accounts.views import *


urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index, name="homepage"),
    path('signup/', signup_user, name="signup"),
    path('login/', login_user, name="login"),
    path('logout/', logout_user, name="logout"),
    path('add-product/', add_product, name="add-product"),
    path('product/', get_product, name="product"),
    path('order/<int:product_id>', add_order, name="add-order"),
    path('order/', get_order, name="order"),
]

Yaradılacaq template faylları
  • myproject/accounts/templates/add-product.html
  • myproject/accounts/templates/base.html
  • myproject/accounts/templates/index.html
  • myproject/accounts/templates/login.html
  • myproject/accounts/templates/order.html
  • myproject/accounts/templates/product.html
  • myproject/accounts/templates/signup.html

Html examples: https://getbootstrap.com/

Static folder
  • myproject/accounts/static/
  • styles.css

add-product.html
Template — add-product.html
accounts/templates/add-product.html
{% extends 'base.html'%}

{% block title %}
Add Product
{% endblock %}

{% block content %}

<form method="post">
    {% csrf_token %}
    <label for="name">Product Name</label>
    <input type="text" name="name">
    <label for="name">Product Price</label>
    <input type="text" name="price">
    <button type="submit">Submit</button>
</form>

<a href="{% url 'logout' %}">Logout</a>
{% endblock %}
base.html
Template — base.html
accounts/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %} {% endblock %}</title>
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>
index.html
Template — index.html
accounts/templates/index.html
{% extends 'base.html'%}

{% block title %}
Homepage
{% endblock %}

{% block content %}
Homepage
{% if user %}
<p>Welcome {{user}}</p>
{% endif %}

<a href="{% url 'logout' %}">Logout</a>
{% endblock %}
login.html
Template — login.html
accounts/templates/login.html
{% extends 'base.html'%}

{% block title %}
Login
{% endblock %}

{% block content %}
<form method="post">
    {% csrf_token %}
    <label for="username">Username</label>
    <input type="text" name="username">
    <label for="password">Password</label>
    <input type="password" name="password">
    <button type="submit">Submit</button>
</form>
{% endblock %}
order.html
Template — order.html
accounts/templates/order.html
{% extends 'base.html' %}

{% block title %}
Orders
{% endblock %}

{% block content %}
{% for order in orders %}
    <p><strong>Order ID:</strong> {{ order.id }}</p>

    {% for product in order.product.all %}
        <p>
            Product Name: {{ product.name }}<br>
            Product Price: ${{ product.price }}
        </p>
    {% empty %}
        <p>No products in this order.</p>
    {% endfor %}

    <hr>
{% endfor %}
{% endblock %}
product.html
Template — product.html
accounts/templates/product.html
{% extends 'base.html'%}

{% block title %}
Product
{% endblock %}

{% block content %}
{% for product in products %}
<ul>
    <li>{{product.name}}</li>
    <li>{{product.price}}</li>
    <a href="{% url 'add-order' product.id%}">Order Now</a>
</ul>
{% endfor %}

<a href="{% url 'logout' %}">Logout</a>
{% endblock %}
signup.html
Template — signup.html
accounts/templates/signup.html
{% extends 'base.html'%}

{% block title %}
Sign Up
{% endblock %}

{% block content %}
<form method="post">
    {% csrf_token %}
    <label for="username">Username</label>
    <input type="text" name="username">
    <label for="password">Password</label>
    <input type="password" name="password">
    <label for="email">Email</label>
    <input type="text" name="email">
    <button type="submit">Submit</button>
</form>
{% endblock %}

accounts/views.py faylına aşağıdakı kodu əlavə edirik:

VS Code — views.py
accounts/views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.decorators import login_required
from .models import Customer, Product, Order


def signup_user(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        email  = request.POST.get("email")

        user = User.objects.create_user(username=username, password=password)
        user.save()
        customer = Customer.objects.create(user=user, Name=username, Email=email)
        customer.save()
        return redirect("login")
    return render(request, "signup.html")


def login_user(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect("/")
    return render(request, "login.html")


@login_required
def index(request):
    return render(request, "index.html", {'user': request.user})


def logout_user(request):
    logout(request)
    return redirect("login")


def add_product(request):
    if request.method == "POST":
        name = request.POST.get("name")
        price = request.POST.get("price")

        product = Product.objects.create(name=name, price=price)
        product.save()
        return redirect("/")
    return render(request, "add-product.html")


def get_product(request):
    products = Product.objects.all()
    return render(request, "product.html", {'products': products})


def add_order(request, product_id):
    customer = Customer.objects.get(user=request.user)
    product = Product.objects.get(id=product_id)
    order = Order.objects.create(
        customer=customer
    )
    order.product.add(product)
    order.save()
    return redirect("order")


def get_order(request):
    orders = Order.objects.filter(customer__user=request.user)
    return render(request, "order.html", {"orders": orders})

Artıq hər şey hazırdır, serveri işə salıb test edə bilərsən:

PowerShell — Runserver
myproject>
1) Django E-commerce\django\myproject> python manage.py runserver

Database-i vizual görmək üçün:

Elvin Babanlı
online • quick replies
×
Hi! I’m Elvin. Ask me anything about projects, stack, or your tasks.