ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 간단한 shop 장바구니 만들기 예제
    Python Django 2022. 10. 23. 14:38

     

    urls.py

    from django.contrib import admin
    from django.urls import path
    from basket_app import views
    
    urlpatterns = [
        path("admin/", admin.site.urls),
        
        path("", views.mainFunc),
        path("page1", views.page1Func),
        path("page2", views.page2Func),
        path("cart", views.cartFunc),
        path("buy", views.buyFunc),
    ]

    페이지의 수만큼 path 작성

     

     

    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} #java의 폼빈, dto, 집합 같은 느낌
        
        productList=[] #상품 정보를 담을 통 같은거
        
        #클라이언트 하나에 하나의 세션만 할당된다.
        #세션은 냉장고, 프러덕리스트는 냉장고 안에 있는 통
        if "shop" in request.session: #이미 샵이라는 통이 있다면
            productList=request.session['shop'] #세션 내에 'shop'이라는 키로 프러덕리스트가 등록되었다. 통이 준비되었고
            productList.append(product) #통을 꺼내서 첫번재 상품을 통에 담았다.
            request.session['shop']=productList # 통을 다시 냉장고(세션)에 넣었다.
        else:
            productList.append(product) #통을 꺼내서 첫번재 상품을 통에 담았다.
            request.session['shop']=productList # 최초 상품일 땐 여기로 온다. 두번째부터 위로 간다.
            
        print(productList)
        context={} #dict type
        context['products']=request.session['shop'] 
        #이미 세션에 들어있다고 생각해서 request.session으로 productList을 꺼낸것이다.
        #상품 통에 있는 거를 꺼내는 것
        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})

    page에서 post 형식으로 받은 name값과 price 값을 cartFunc함수에서 받고 그것을 dict타입에 넣는다.

    여러개가 들어가기 때문에 List 타입을 하나 만들어 다시 그곳에 넣는다.

    처음에는 세션이 만들어지지 않기 때문에 else문으로 바로 가서 세션을 생성하고 그 뒤부터는 이미 생성되어있기에 그곳에 넣어주는 형식이다. 그리고 그 값을 cart.html로 가지고 간다.

    buy.html 에서 세션 값을 받으면 값들이 여러개가 한번에 묶음으로 오기 때문에 buyFunc함수에서 for문을 돌려 값들을 분류해야 된다. 그리고 더해진 값을 html로 보내준다.

     

     

    main.html

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    <p>상품 판매</p>
    <ul>
    	<li>
    		<a href="page1">
    			<img src="/static/images/pic1.jpg" style="width: 40%" title="서둘러">
    		</a>
    	</li>
    	<li>
    		<a href="page2">
    			<img src="/static/images/pic2.jpg" style="width: 40%" title="빨리사">
    		</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>
    window.onload = function(){
    	document.querySelector("#btnOk").onclick = function(){
    		frm.submit();
    	}
    }
    </script>
    </head>
    <body>
    <table>
    	<tr>
    		<td>
    			<img src="/static/images/pic1.jpg" style="width: 100">
    		</td>
    		<td>
    			<pre>
    공용 ON 씬에어(THINAIR) GMW22593
    23% 할인가 215,600원		
    L.POINT 최대307P
    			</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="215600"/>
    				<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>
    window.onload = function(){
    	   document.querySelector("#btnOk").onclick = function(){
    	      frm.submit();
    	   }
    	}
    
    </script>
    </head>
    <body>
    <table>
    	<tr>
    		<td>
    			<img src="/static/images/pic2.jpg" style="width: 100">
    		</td>
    		<td>
    			<pre>
    반스 클래식 올드스쿨 스니커즈 VN000D3HY28
    48,900원		
    L.POINT 최대24P
    			</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="48,900"/>
    				<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>* 장바구니 목록 *</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>
    <p>결제 총액 : {{total}}원 결제 완료!</p>
    고객님 감사합니다.
    <hr>
    <a href="/">메인페이지</a>
    </body>
    </html>

    혹시 err가 발생하면 migrate를 실행했었는지 다시한번 확인해보자

     

     

    댓글

Designed by Tistory.