49.Django(장고) - ecommerce 프로젝트 - 쇼핑몰 - Login 유저 장바구니 처리 및 DB 연결

JungSik Heo·2024년 12월 10일

1.cart\models.py

from django.db import models

#dev_40
# Create your models here.
class Cart(models.Model):
    user  = models.ForeignKey('auth.User', on_delete=models.CASCADE, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"카트아이디:{self.id}    유저이름:{self.user.username}"
    

class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE,related_name='cart_items')
    product = models.ForeignKey('store.Product', on_delete=models.CASCADE,related_name='items')
    quantity = models.IntegerField(default=1)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    def __str__(self):
        return f"자기아이디:{self.id}    카트아이디:{self.cart.id}   제품아이디:{self.product.id}   제품이름:{self.product.name}   제품수량:{self.quantity}"

2. accounts\urls.py

파일 이름 정리 및 login 처리

from django.contrib import admin
from django.urls import include, path
from django.contrib.auth import views as auth_views
from accounts import views

app_name = 'accounts'

#dev_40 이름 통일
urlpatterns = [
     #path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), 
     path('login/', views.login_user, name='login'), 
     path('logout/', views.logout_user, name='logout'),
     path('register/', views.register_user, name='signup'),
]

3.accounts\views.py

login_user 함수 추가

from django.contrib.auth import authenticate, login, logout
from django.shortcuts import redirect, render

from accounts.forms import UserForm
from django.contrib import messages

from cart.cart import Cart
from cart.models import Cart as CartModel, CartItem
#dev_40
import json

# Create your views here.
def logout_user(request):
    logout(request)
    return redirect('/')

def register_user(request):
    if request.method == "POST":
        form = UserForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)  # 사용자 인증
            login(request, user)  # 로그인
            return redirect('/')
    else:
        form = UserForm()
    return render(request, 'accounts/signup.html', {'form': form})

#dev_40
def login_user(request):

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request,username=username,password=password)
        
        if user is not None:
            login(request, user) 
            
            saved_cart_item = CartItem.objects.filter(cart__user__id=request.user.id)
            
            if saved_cart_item:
                
                #Get the cart
                cart = Cart(request)

                for item in saved_cart_item:
                    print("===========",item.product.id)
                    print("===========",item.quantity)                    
                    cart.add(product=item.product,quantity=item.quantity) 

            messages.success(request,"You Have been logged in")
            return redirect('/')
        else:
            messages.success(request,("There was an error, please try again"))
            return redirect('login')
    else:    
        return render(request, 'accounts/login.html',{})

4. cart\cart.py

각각의 함수에 로그인된 유저처리
 #Deal with logged in user
        if self.request.user.is_authenticated:
        
from cart.models import CartItem
from store.models import Product
from cart.models import Cart as CartModel


class Cart():
    def __init__(self, request):
        self.session = request.session
        
        #dev_40
        #Get request
        self.request = request

        # Get the current session key if it exists
        cart = self.session.get('session_key')

        # If the session key does not exist, create one!
        if 'session_key' not in request.session:
            cart = self.session['session_key'] = {}

        print(cart)

        #Make sure cart is available on all pages of site    
        self.cart = cart

    def add(self,product, quantity):

        product_id  = str(product.id)
        product_qty = str(quantity)
        
        #>>> a[3] = [1, 2, 3]
        #>>> a
        #{1: 'a', 2: 'b', 'name': 'pey', 3: [1, 2, 3]}

        if product_id in self.cart:
            pass
        else:
            #self.cart[product_id] = {'price': str(product.price)}
            self.cart[product_id] = int(product_qty)
        
        self.session.modified = True
    
    def __len__(self):
        return len(self.cart)
    
    def get_prods(self):
        
        # Get ids from cart
        product_ids = self.cart.keys()

        # use ids to lookup products in database model
        products =  Product.objects.filter(id__in=product_ids)

        #Return those looked up products
        return products
    
    def get_quants(self):
        quantities = self.cart
        return quantities
    
    def update(self, product, quantity):
        product_id =  str(product)
        product_qty = int(quantity)

        #Get cart
        ourcart = self.cart
        #{'4':3, '5':4}}
        
        #update dictionary
        ourcart[product_id] = product_qty

        self.session.modified = True
        thing = self.cart

        #dev_40
        if self.request.user.is_authenticated:
                
            # Get the current user profile
            cart, created =  CartModel.objects.get_or_create(user=self.request.user)
            print(cart)
            cart_item, created = CartItem.objects.get_or_create(cart=cart,product_id=product_id)
            cart_item.quantity = quantity
            print(cart_item)
            cart_item.save()

        return thing
    
    def delete(self,product):
        product_id = str(product)

        if product_id in self.cart:
            del self.cart[product_id]

        self.session.modified = True

        #dev_40
        # Deal with logged in user
        if self.request.user.is_authenticated:
                
            # Get the current user profile
            cart, created =  CartModel.objects.get_or_create(user=self.request.user)
            print(cart)
            cart_item, created = CartItem.objects.get_or_create(cart=cart,product_id=product_id)
            print(cart_item)
            cart_item.delete()



    def cart_total(self):
        product_ids = self.cart.keys()
        products = Product.objects.filter(id__in=product_ids)

        quantities = self.cart

        total = 0

        for key, value in quantities.items():
            #Convert key string into so we 
            key = int(key)

            for product in products:
                if product.id  == key:
                    if product.is_sale:
                        total = total + (product.sale_price * value)
                    else:
                        total = total + (product.price * value)

        return total        
    #https://www.youtube.com/watch?v=PgCMKeT2JyY
    #dev_40
    def add_to_cart(self,product,quantity):
        product_id  = str(product.id)
        product_qty = str(quantity)
            
        if product_id in self.cart:
            pass
        else:
            self.cart[product_id] = int(product_qty)
            
        self.session.modified = True

        #product = Product.objects.get(id=product_id)

        # Deal with logged in user
        if self.request.user.is_authenticated:
                
            # Get the current user profile
            cart, created =  CartModel.objects.get_or_create(user=self.request.user)
            print(cart)
            #Object: The existing object that was found with the given kwargs
            #Boolean: Specifies whether a new object was created 
            cart_item, created = CartItem.objects.get_or_create(cart=cart,product=product)
            print(cart_item)
            cart_item.quantity = int(quantity)
            cart_item.save()

5.cart\views.py

cart_add(request):함수 수정

def cart_add(request):
    
    cart  = Cart(request)

    if request.POST.get('action') == 'post':
        
        #get stuff
        product_id = int(request.POST.get('product_id'))
        print('product_id', product_id)
        
        product_qty = int(request.POST.get('product_qty'))
        # lookup proudct in DB
        product = get_object_or_404(Product,id=product_id)

        print("프로덕트",product)

        #save to session
        #cart.add(product=product, quantity = product_qty)
        #dev_40 DB 저장모듈 추가
        cart.add_to_cart(product=product, quantity = product_qty)



        #Get Cart Quantity
        cart_quantity = cart.__len__()
        response = JsonResponse({'qty': cart_quantity})
        #추가 dev_38
        messages.success(request,"장바구니에 해당 상품이 추가되었습니다.")
        return response
    

로그인 후 로그아웃 -> 다시 로그인 -> 장바구니에 담긴것이 제대로 나오는가 확인

profile
쿵스보이(얼짱뮤지션)

0개의 댓글