STEP 1 coucpon app
python manage.py startapp coupon
STEP 2 config/settings.py
INSTALLED_APPS = [
'coupon',
]
STEP 3 cart/cart.py 에 추가
from coupon.models import Coupon
if not cart :
cart = self.session[settings.CART_ID] = {}
self.cart = cart
self.coupon_id = self.session.get('coupon_id')
# 장바구니 비우기
def clear(self):
self.session[settings.CART_ID] = {}
self.session.modified = True
self.session['coupon_id'] = None # 쿠폰 추가
// 쿠폰 정보 삭제를 위해 session에 저장된 coupon_id 를 None 으로 지정한 것
STEP 4 coupon/models.py
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
# Create your models here.
# coupon
class Coupon(models.Model):
code = models.CharField(max_length=50,unique=True)
use_from= models.DateField()
use_to = models.DateField()
amount = models.IntegerField(validators=[MinValueValidator(0), MaxValueValidator(100000)])
active = models.BooleanField()
def __str__(self):
return self.code
STEP 5 DB 반영
python manage.py makemigrations coupon
python manage.py migrate
STEP 6 coupon/forms.py
from django import forms
class AddCouponForm(forms.Form):
code = forms.CharField(label='쿠폰 코드 입력')
STEP 7 coupon/views.py
from django.shortcuts import render, redirect
from django.utils import timezone
from django.views.decorators.http import require_POST
from .models import Coupon
from .forms import AddCouponForm
# Create your views here.
# 쿠폰 추가 뷰
@require_POST
// view 가 POST 메서드만 허용하도록 하는 데코레이터
def add_coupon(request):
now = timezone.now()
form = AddCouponForm(request.POST)
if form.is_valid():
code = form.cleaned_data['code']
// 입력한 쿠폰 코드를 이용해 쿠폰 조회
try:
coupon = Coupon.objects.get(code__iexact=code, use_from__lte=now,
use_to__gte=now, active=True)
request.session['coupon_id'] = coupon.id
except Coupon.DoesNotExist:
request.session['coupon_id'] = None
return redirect('cart:detail')
STEP 8 url 연결
# coupon/urls.py
from django.urls import path
from .views import add_coupon
app_name = 'coupon'
urlpatterns =[
path('add/',add_coupon, name='add'),
]
# config/urls.py
path('coupon/', include('coupon.urls')),
STEP 9 cart/cart.py
@property
def coupon(self):
if self.coupon_id:
return Coupon.objects.get(id=self.coupon_id)
return None
def get_discount_total(self):
if self.coupon:
if self.get_product_total() >= self.coupon.amount:
return self.coupon.amount
return Decimal(0)
def get_total_price(self):
return self.get_product_total() - self.get_discount_total()
STEP 10 cart/views.py
def detail(request):
cart = Cart(request)
add_coupon = AddCouponForm()
for product in cart:
product['quantity_form'] = AddProductForm(initial={'quantity':product['quantity'], 'is_update':True})
return render(request, 'cart/detail.html',{'cart':cart, 'add_coupon':add_coupon})
STEP 11 cart/detail.html
<p>
사용 쿠폰 :
</p>
<form action="{% url 'coupon:add' %}" method = "post">
{{add_coupon}}
<input class ="btn btn-outline-info" type="submit" value ="사용">
{% csrf_token %}
</form>
<p class="text-right">
<a href="{% url 'shop:product_all' %}" class="btn btn-secondary">Continue shopping</a>
<a href="#" class="btn btn-info">Checkout</a>
</p>
STEP 12 coupon/admin.py
# 쿠폰은 보통 관리자가 생성하므로 관리자 페이지에 쿠폰 등록
from django.contrib import admin
from .models import Coupon
# Register your models here.
class CouponAdmin(admin.ModelAdmin):
list_display = ['code','use_from','use_to','amount','active']
list_filter = ['active','use_from','use_to']
search_fields = ['code']
admin.site.register(Coupon, CouponAdmin)
admin 에 쿠폰까지 등록해서 할인된 금액까지 화면에 보여질 수 있게 코드 작성하며 스터디 진행
좋은 정보 얻어갑니다, 감사합니다.