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.
Başlanğıc
Əvvəlcə Django E-commerce üçün əsas strukturumuzu yaradırıq:
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
accounts app artıq hazırdır.
Konfiqurasiya
İlk olaraq accounts app-i INSTALLED_APPS hissəsinə əlavə edirik:
INSTALLED_APPS = [
...
'accounts',
]
Database
1) İlk migrate
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:
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
2) Django E-commerce\django\myproject> python manage.py makemigrations
3) Django E-commerce\django\myproject> python manage.py migrate
Admin panel
Admin panelə giriş üçün superuser yaradırıq:
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.
Routing
accounts.views-dən bütün view-ları import edib URL pattern-ləri yazırıq:
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"),
]
Frontend
Yaradılacaq template faylları
myproject/accounts/templates/add-product.htmlmyproject/accounts/templates/base.htmlmyproject/accounts/templates/index.htmlmyproject/accounts/templates/login.htmlmyproject/accounts/templates/order.htmlmyproject/accounts/templates/product.htmlmyproject/accounts/templates/signup.html
Html examples: https://getbootstrap.com/
Static folder
myproject/accounts/static/styles.css
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
<!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
{% 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
{% 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
{% 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
{% 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
{% 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 %}
Back-end
accounts/views.py faylına aşağıdakı kodu əlavə edirik:
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})
Test & Debug
Artıq hər şey hazırdır, serveri işə salıb test edə bilərsən:
1) Django E-commerce\django\myproject> python manage.py runserver
Database-i vizual görmək üçün: