본문 바로가기
[ 빅데이터 ]

[빅데이터] 프로젝트 - 상품등록 페이지 만들기(1)

by 히앤님 2020. 10. 19.
반응형
SMALL

Spring에서 만들었던 쇼핑몰 페이지를 그대로 디장고(Django)로 바꿔 옮기자.


1. 초기 상태

현재 받은 파일에서는 회원가입 기능과 로그인 기능은 구현 되어 있는 상태.

urls.py에 대부분의 페이지 path가 연결되어 있다.

 

 

▼views.py

더보기

1. 아직 기능 구현 하지 않은 것들은 jsp 파일로 렌더링만 해놓음.

from django.shortcuts import render, redirect

# Create your views here.
from django.views.decorators.csrf import csrf_protect

from shoppingmallPrj.models import getLoginChk, client_insert


def home(request):
    return render(request, 'shoppingmallPrj/index.jsp')


def shop_cart(request):
    return render(request, 'shoppingmallPrj/shop_cart.jsp')


def my_page(request):
    return render(request, 'shoppingmallPrj/my_page.jsp')


def product_details(request):
    return render(request, 'shoppingmallPrj/product_details.jsp')


def shop(request):
    return render(request, 'shoppingmallPrj/shop.jsp')


def index(request):
    return render(request, 'shoppingmallPrj/index.jsp')


def manager(request):
    return render(request, 'shoppingmallPrj/manager.jsp')


def qna_board(request):
    return render(request, 'shoppingmallPrj/qna_board.jsp')


def checkout(request):
    return render(request, 'shoppingmallPrj/checkout.jsp')


def shop_type(request):
    return render(request, 'shoppingmallPrj/shop_type.jsp')


def shop_search(request):
    return render(request, 'shoppingmallPrj/shop_search.jsp')


def manager_customer_detail(request):
    return render(request, 'shoppingmallPrj/manager_customer_detail.jsp')


def manager_product_detail(request):
    return render(request, 'shoppingmallPrj/manager_product_detail.jsp')


def manager_pay_all(request):
    return render(request, 'shoppingmallPrj/manager_pay_all.jsp')


def manager_add_product(request):
    return render(request, 'shoppingmallPrj/manager_add_product.jsp')


def manager_qna_board(request):
    return render(request, 'shoppingmallPrj/manager_qna_board.jsp')

 

2. 로그인 / 로그인샵 / 로그인카트 * 로그아웃 / 회원가입 -> 총 9개

@csrf_protect
def login(request):
    if 'client_id' in request.session:
        return redirect('/index')
    if request.method == 'POST':
        client_id = request.POST['client_id']
        password = request.POST['password']
        print('client_id :', client_id)
        print('password :', password)
        # --------------------------------------------------------------
        res = getLoginChk(client_id, password)
        print('=' * 30)
        print(res)
        if len(res) > 0:
            print('로그인 성공')
            request.session['client_id'] = client_id
            request.session['client_name'] = res[0][0]
            return redirect('/shoppingmallPrj')
        else:
            print('로그인 실패')
            msg = '아이디나 비밀번호가 잘못 되었습니다.'
            return render(request, "shoppingmallPrj/index.jsp", {"error": msg})
    return render(request, 'shoppingmallPrj/index.jsp')


@csrf_protect
def login_shop(request):
    if 'client_id' in request.session:
        return redirect('/shoppingmallPrj/shop')
    if request.method == 'POST':
        client_id = request.POST['client_id']
        password = request.POST['password']
        print('client_id :', client_id)
        print('password :', password)
        # --------------------------------------------------------------
        res = getLoginChk(client_id, password)
        print('=' * 30)
        print(res)
        if len(res) > 0:
            print('로그인 성공')
            request.session['client_id'] = client_id
            request.session['client_name'] = res[0][0]
            return redirect('/shoppingmallPrj/shop')
        else:
            print('로그인 실패')
            msg = '아이디나 비밀번호가 잘못 되었습니다.'
            return render(request, "shoppingmallPrj/shop.jsp", {"error": msg})
    return render(request, 'shoppingmallPrj/shop.jsp')


@csrf_protect
def login_cart(request):
    if 'client_id' in request.session:
        return redirect('/shoppingmallPrj/shop_cart')
    if request.method == 'POST':
        client_id = request.POST['client_id']
        password = request.POST['password']
        print('client_id :', client_id)
        print('password :', password)
        # --------------------------------------------------------------
        res = getLoginChk(client_id, password)
        print('=' * 30)
        print(res)
        if len(res) > 0:
            print('로그인 성공')
            request.session['client_id'] = client_id
            request.session['client_name'] = res[0][0]
            return redirect('/shoppingmallPrj/shop_cart')
        else:
            print('로그인 실패')
            msg = '아이디나 비밀번호가 잘못 되었습니다.'
            return render(request, "shoppingmallPrj/shop_cart.jsp", {"error": msg})
    return render(request, 'shoppingmallPrj/shop_cart.jsp')


# 로그아웃 처리
def logout(request):
    del request.session['client_id']
    del request.session['client_name']
    return redirect('/shoppingmallPrj')


def logout_shop(request):
    del request.session['client_id']
    del request.session['client_name']
    return redirect('/shoppingmallPrj/shop')


def logout_cart(request):
    del request.session['client_id']
    del request.session['client_name']
    return redirect('/shoppingmallPrj/shop_cart')


@csrf_protect
def sign_in(request):
    client_info = (request.POST['client_id'], request.POST['password'],
                   request.POST['client_name'], request.POST['addr'],
                   request.POST['phone'], request.POST['email'])
    client_insert(client_info)
    return redirect('/shoppingmallPrj')


@csrf_protect
def sign_in_shop(request):
    client_info = (request.POST['client_id'], request.POST['password'],
                   request.POST['client_name'], request.POST['addr'],
                   request.POST['phone'], request.POST['email'])
    client_insert(client_info)
    return redirect('/shoppingmallPrj/shop')


@csrf_protect
def sign_in_cart(request):
    client_info = (request.POST['client_id'], request.POST['password'],
                   request.POST['client_name'], request.POST['addr'],
                   request.POST['phone'], request.POST['email'])
    client_insert(client_info)
    return redirect('/shoppingmallPrj/shop_cart')

 

▼urls.py

더보기

등록된 path 들. 이번 과제에서 내가 정의할 것은 상품 등록에 해당하는 manager_add_product와 등록된 상품을 볼 수 있는 manager_product_detail를 정의해야 한다.

from django.urls import path

from shoppingmallPrj import views
#
urlpatterns=[
    path("",views.home),
    path("shop_cart",views.shop_cart),
    path("my_page",views.my_page),
    path("product_details",views.product_details),
    path("shop",views.shop),
    path("index",views.index),
    path("manager",views.manager),
    path("qna_board", views.qna_board),
    path("checkout", views.checkout),
    path("login", views.login),
    path("logout", views.logout),
    path("logout_shop", views.logout_shop),
    path("logout_cart", views.logout_cart),
    path("sign_in", views.sign_in),
    path("login_shop", views.login_shop),
    path("login_cart", views.login_cart),
    path("shop_type", views.shop_type),
    path("shop_search", views.shop_search),
    path("manager_customer_detail", views.manager_customer_detail),
    path("manager_product_detail", views.manager_product_detail),
    path("manager_add_product", views.manager_add_product),
    path("manager_qna_board", views.manager_qna_board),
]

2.  manager_add_product의 input 데이터 DB로 보내기

1) add_product 로 이동

상품 추가 페이지에서 상품 등록을 누르면,

add_product로 가도록 링크를 걸어두었다.

def manager_add_product(request):
    return render(request, 'shoppingmallPrj/manager_add_product.jsp')

manage_add_product.jsp 로 넘어오면 add_priduct로 쏜다.

따라서 add_product 라는 이름의 뷰를 지정해서 기능을 구현해야 한다.

 

 

-> 입력값 오라클로 보내기

action 누르면 add_product(정의하기-> insert 하는거, 뷰에서 실행해서 리다이렉트 관리자 페이지로)로 가는거 그걸 뷰에서 정의 그리고 모델에서 오라클로 보내고.

 

2) 상품의 시퀀스 만들기(Product_info_seq)

create sequence Product_info_seq increment by 1 start with 1;

 

3) 상품을 추가하는 함수 만들기(views.py)

product_info에 각 카테고리의 값을 post로 담아서 product_insert의 안의 함수로 넣어줌.

다 되면 manager로 이동

@csrf_exempt
def add_product(request):
    product_info = (request.POST['product_name'],
                    request.POST['category_gender_id'], request.POST['category_type_id'],
                    request.POST['buy_price'], request.POST['sell_price'],
                    request.POST['product_info'], request.POST['stock'], request.POST['buy_place'])
    product_insert(product_info)
    return redirect('/shoppingmallPrj/manager')

 

4) 상품을 추가하는 함수 만들기(models.py)

views.py에서 만들어 놓은 product_info라는 매개변수의 값을 가져와서 sql문 실행

def product_insert(product_info):
    print(product_info)
    conn = ora.connect(database)
    cursor = conn.cursor()
    sql = "insert into product_info values(Product_info_seq.nextVal, :1,:2,:3,:4,:5,:6,:7,:8)"
    cursor.execute(sql, product_info)
    cursor.close()
    conn.commit()
    conn.close()

5) urls.py 등록

6) 실행

데이터 입력
오라클에 잘 들어간다


[ 에러 모음 ]


1. MultiValueDictKeyError

해결책 : PRODUCT_NAME 등 컬럼명을 전부 소문자로 바꿔줬더니 에러 해결.

 

 

2. ORA-01400: cannot insert NULL into

POST.get('PRODUCT_NAME','')도 써봤지만 not null로 지정해주었기 때문에 소용이 없었다. 그냥 post로 하고 1번 방법으로 해결.

[ 차이점 ]
request.POST['title']

request.POST['title']는 request 로 넘어온 POST 값을 딕셔너리(dictionary)형태로 반환을 해 준다. 딕셔너리는 파이썬 (python) 문법에 의해서 key 값과 value 값으로 존재하기 때문에 ['...'] 인 key 값을 이용해서 value 값을 리턴해 준다. 그런데 여기서 value 값이 존재하지 않는다면 MultiValueDictKeyError을 일으킨다.

request.POST.get('title', '')

반면에 request.POST.get('title') 에선 존재하지 않는 key 값을 반환해야 한다면 None 을 반환해 주고, request.POST.get('title', '') 로 할 경우엔 존재하지 않는 key 값을 반환할때 default 값을 지정해 줄 수 있다.

 

3. CSRF 검증에 실패했습니다. 요청을 중단하였습니다.

CSRF의 예외처리를 안했다. @csrf_exempt를 붙이고 수입하면 해결.

 

 

4. IntegrityError

 

add_product에서 FK인 category_type_id나 category_gender_id 를 아무 값도 안넣고 null로 두어서 에러남.

DB를 보면 id 컬럼이 NOT NULL로 되어있음을 확인할 수 있다.

=> user_id가 NULL이 되지 않도록 오라클에 아무 값이나 넣어주자.

추가하고 commit 한다

 


이제 

 

3.  manager_product_detail의 input 데이터 DB로 보내기

1) models.py에 필요한 값들 불러오기

# 상품 세부 내역
def product_detail_show():

    conn = ora.connect(database)
    cursor = conn.cursor()
    sql = "select * from product_info order by 1 desc"
    cursor.execute(sql)
    result = cursor.fetchall()
    print(result)
    cursor.close()
    conn.close()
    return result

 

 

2) manager_product_detail에 models.py에서 받아온 값들 집어넣기(views.py)

그 후에 product_detail에 넣은 값들 불러와.

def manager_product_detail(request):
    product_detail=product_detail_show()
    return render(request, 'shoppingmallPrj/manager_product_detail.jsp',{'product_detail':product_detail})

 

3)manager_product_detail.jsp 변경

받아왔으니까 연결시킨 jsp 중 어디에 출력할건지 범위 설정해주기


                            <tbody>
                            	<c:forEach items="${product_infoList }" var="product_detail">
                            	{% for p in product_detail%}
                                <tr>
                                {% for i in p%}
									<td>{{i}}</td>


                                  {% endfor%}
                                  <!-- 추가 -->
									<td>
										<c:choose>
											<c:when test="${product_info.product_fsize==0}">첨부파일 없음</c:when>
					    					<c:otherwise>
                                  				<img src="resources/upload/${product_info.product_fname}" width='50'>
                                  			</c:otherwise>
									 	</c:choose>					  
									</td>					
									<td>${product_info.product_fsize}byte</td>
                                </tr>
                                  <!-- 추가 끝 -->

                                {% endfor %}
                                
                                
                                
                                </c:forEach>

4) urls.py에 path 등록하기

    path("manager_product_detail", views.manager_product_detail),

 

5) 결과

 

 

+추가

원피스만 등록된다!

2번 3번도 등록해주기.

카테고리 타입에 1번만 등록해놨다...ㅎㅎ...

반응형
LIST

댓글