본문 바로가기

Django

django4 - session 예제(간이 쇼핑몰, 장바구니 기능)

 

 

urls.py

"""django4_shop URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from basket_app import views
  
urlpatterns = [
    path("admin/", admin.site.urls),
    
    path("page1", views.page1Func),
    path("page2", views.page2Func),
    path("cart", views.cartFunc),
    path("buy", views.buyFunc),
    path("", views.mainFunc),
]

 

 

views.py

from django.shortcuts import render

# Create your views here.
def mainFunc(request):
    return render(request, 'main.html')

def page1Func(request):
    return render(request, 'page1.html')

def page2Func(request):
    return render(request, 'page2.html')

def cartFunc(request):
    name = request.POST["name"]
    price = request.POST["price"]
    product = {'name':name, 'price':price}
    
    productList = []
    
    if "shop" in request.session:
        productList = request.session['shop']  # 세션 내에 'shop'이라는 키로 productList 등록
        productList.append(product)
        request.session['shop'] = productList
    else:
        productList.append(product)
        request.session['shop'] = productList
        
    print(productList)
    context = {}
    context['products'] = request.session['shop']
    return render(request, 'cart.html', context)

def buyFunc(request):
    if "shop" in request.session:
        productList = request.session['shop']
        total = 0   
    
        for p in productList:
            total += int(p['price'])
        
        print('결제 총액 : ', total)
        request.session.clear()  # 세션 내의 모든 키 삭제
        # del request.session['shop']  # 특정 키를 가진 세션 내용 삭제
        
    return render(request, "buy.html", {'total':total})

 

 

main.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
상품 판매<p/>
<ul>
	<li>
		<a href="page1">
			<img src="/static/images/pic1.jpeg" style="width: 40%" title="서둘러"/>
		</a>
	</li>
	<li>
		<a href="page2">
			<img src="/static/images/pic2.jpeg" style="width: 40%" title="서둘러2"/>
		</a>
	</li>
</ul>
<pre>





</pre>
<hr>문의 : 02-111-1111 담당:보노
</body>
</html>

 

 

page1.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
	document.querySelector("#btnOk").onclick = function(){
		frm.submit();
	}
}
</script>
</head>
<body>
<table>
	<tr>
		<td>
			<img src="/static/images/pic1.jpeg" style="width: 120%"/>
		</td>
		<td>
			<pre>
			[롯데백화점] 22F/W BAG&SHOES FAIR 슈콤마보니
			할인률10%
			정가298,000원
			최종가268,200원
			</pre>
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<form action="cart" name="frm" method="post">{% csrf_token %}
			<input type="hidden" name="name" value="슈콤마보이">
			<input type="hidden" name="price" value="268200">
			<input type="button" id="btnOk" value="장바구니에 담기">
			<input type="button" value="홈으로" onclick="history.back()">
			</form>
		</td>
	</tr>
</table>
</body>
</html>

 

 

page2.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
window.onload = function(){
	document.querySelector("#btnOk").onclick = function(){
		frm.submit();
	}
}
</script>
</head>
<body>
<table>
	<tr>
		<td>
			<img src="/static/images/pic2.jpeg" style="width: 100%"/>
		</td>
		<td>
			<pre>
			[APPLE] NEW 신상 에어팟 프로2
			할인률10%
			정가300,000원
			최종가270,000원
			</pre>
		</td>
	</tr>
	<tr>
		<td colspan="2">
			<form action="cart" name="frm" method="post">{% csrf_token %}
			<input type="hidden" name="name" value="에어팟 프로2">
			<input type="hidden" name="price" value="270000">
			<input type="button" id="btnOk" value="장바구니에 담기">
			<input type="button" value="홈으로" onclick="history.back()">
			</form>
		</td>
	</tr>
</table>
</body>
</html>

 

 

cart.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
* 장바구니 목록 *<p/>
<table border="1">
	<tr><th>상품명</th><th>가격</th></tr>
	{% if products %}
	{% for p in products %}
	<tr>
		<td>{{p.name}}</td>
		<td>{{p.price}}</td>
	</tr>
	{% endfor %}
	{% else %}
	<tr>
		<td colspan="2">자료 없음</td>
	</tr>
	{% endif %}
</table>
<br>
<a href="buy">결제하기</a>
<a href="/">메인 페이지</a>
</body>
</html>

 

 

buy.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
결제 총액 : {{total}}원 결제 완료!<br>
고객님 감사합니다.
<hr>
<a href="/">메인 페이지</a>
</body>
</html>

 

 

'Django' 카테고리의 다른 글

django6 - Maria DB (방명록)  (0) 2022.10.17
django5 - DB  (0) 2022.10.17
django3 - session  (0) 2022.10.17
django2 - GET, POST, django 기본 구조  (0) 2022.10.17
django1 - static 폴더 (image, css, js)  (0) 2022.10.14