import requests
from django.urls import reverse_lazy
from django.views.generic.edit import CreateView
from django.conf import settings
from django.http import JsonResponse
from django.views import View
from django.shortcuts import render
from django.http import HttpResponse
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from django.shortcuts import render, redirect
from django.contrib.auth.hashers import make_password
from django.contrib import messages
from django.shortcuts import render, redirect
from django.contrib.auth import login as auth_login,authenticate,logout
from .models import CustomUser  # CustomUser 모델 임포트
from django.contrib.auth.hashers import check_password
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.http import HttpRequest, HttpResponse
from .models import Product
from .forms import ProductForm
def index(request):
    return render(request, 'myapp/index.html')

def login(request: HttpRequest) -> HttpResponse:
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')

        if username and password:
            # 사용자 인증
            user = authenticate(request, username=username, password=password)
            if user is not None:
                # 로그인 처리
                auth_login(request, user)
                return redirect('index')  # 로그인 성공 시 리디렉트할 페이지
            else:
                messages.error(request, "사용자 이름 또는 비밀번호가 잘못되었습니다.")
        else:
            messages.error(request, "모든 필드를 입력해주세요.")

    return render(request, 'myapp/login.html')

def logout_view(request: HttpRequest) -> HttpResponse:
    logout(request)
    return redirect('index')  # 로그아웃 후 리디렉트할 페이지

def apply(request):
    return render(request, 'myapp/apply.html')

def mypg(request):
    return render(request, 'myapp/mypg.html')

def loginedindex(request):
    return render(request, 'myapp/loginedindex.html')

def product_registration(request):
    product_link = ''
    product_name = ''
    product_price = ''
    product_image_url = ''
    shipping_fee = ''
    
    if request.method == 'POST':
        product_link = request.POST.get('productLink')

        # Selenium을 사용하여 상품 정보 스크래핑
        options = Options()
        options.headless = True  # 브라우저를 실제로 열지 않으려면 True로 설정
        driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

        try:
            driver.get(product_link)

            # 상품명과 가격을 스크래핑하는 부분
            product_name = driver.find_element(By.CSS_SELECTOR, "h3.prod_tit .title").text  # 상품명 선택자 수정 필요
            # 가격을 스크래핑하고 쉼표와 "원" 제거
            product_price = driver.find_element(By.CSS_SELECTOR, "span.lwst_prc em.prc_c").text  # 가격 선택자 수정 필요
            product_price = product_price.replace(',', '').strip()

            # 이미지 URL 스크래핑
            product_image_url = driver.find_element(By.CSS_SELECTOR, "#baseImage").get_attribute("src")  # 이미지 URL 선택자 수정 필요
            
            # 배송비 스크래핑
            shipping_fee_element = driver.find_element(By.CSS_SELECTOR, ".deleveryBaseSection")  # 배송비 선택자 수정 필요
            shipping_fee = shipping_fee_element.text if shipping_fee_element else "배송비 정보 없음"
            # 배송비의 쉼표와 "원" 제거
            shipping_fee = shipping_fee.replace(',', '').replace('원', '').strip()
            
      
    

             # 스크래핑한 정보를 폼에 채워 넣기
            return render(request, 'myapp/apply.html', {
                'product_link': product_link,
                'product_name': product_name,
                'product_price': product_price,
                'product_image_url': product_image_url,
                'shipping_fee': shipping_fee,
            })

        except Exception as e:
            print(f"Error occurred: {e}")
            return HttpResponse("상품 정보를 가져오는 데 실패했습니다.")
        finally:
            driver.quit()
    
    
    return render(request, 'myapp/apply.html')  # GET 요청 시 폼 렌더링

def my_page(request):
    registered_products = ...  # 등록된 상품 쿼리셋 가져오기
    applied_products = ...  # 신청한 상품 쿼리셋 가져오기
    return render(request, 'myapp/mypg.html', {
        'registered_products': registered_products,
        'applied_products': applied_products,
    })

def register(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        nickname = request.POST.get('nickname')
        password = request.POST.get('password')
        password_confirm = request.POST.get('password_confirm')
        phone = request.POST.get('phone')
        postcode = request.POST.get('sample3_postcode')
        address = request.POST.get('sample3_address')
        detail_address = request.POST.get('sample3_detailAddress')
        extra_address = request.POST.get('sample3_extraAddress')
        # 사용자 이름 중복 체크
        if CustomUser.objects.filter(username=username).exists():
            messages.error(request, "이미 사용 중인 아이디입니다.")
        # 서버 측 유효성 검사
        
        elif not all([username, nickname, password, password_confirm, phone, postcode, address]):
            messages.error(request, "모든 필드를 완전히 입력해야 합니다.")
        elif password != password_confirm:
            messages.error(request, "비밀번호가 일치하지 않습니다.")
        else:
            password_hashed = make_password(password)
            CustomUser.objects.create(
                username=username,
                nickname=nickname,
                password=password_hashed,
                phone=phone,
                postcode=postcode,
                address=address,
                detail_address=detail_address,
                extra_address=extra_address
            )
            return redirect('index')  # 회원가입 성공시 이동할 페이지

    return render(request, 'myapp/register.html')

{% load static %}
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <title>공동구매</title>
        <!-- 부트스트랩 css 사용 -->
       <link rel="stylesheet" href="{% static 'myapp/css/bootstrap.css' %}">
         <!-- jQuery 사용 -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
       <!-- 부트스트랩 JS 사용 -->
        <script src="{% static 'myapp/js/bootstrap.js' %}"></script>
    
        <!-- 사용자 정의 JS 파일 사용 -->
        <script src="{% static 'myapp/js/script.js' %}"></script>

   
        <style>h1{color:red}</style>
        
        
    </head>
    
    <body>
        <nav class="navbar navbar-expand-lg navbar-light bg-light">
            <a class="navbar-brand" href="#">공동구매</a>
            <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
          
            <div class="collapse navbar-collapse" id="navbarSupportedContent">
              <ul class="navbar-nav mr-auto">
                <li class="nav-item active">
                  <a class="nav-link" href="#">홈 <span class="sr-only">(current)</span></a>
                </li>
                {% if request.user.is_authenticated %}
                <li class="nav-item">
                  <a class="nav-link" href="{% url 'apply' %}">상품등록</a>
                </li>
                <li class="nav-item dropdown">
                  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    프로필
                  </a>
                  <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item" href="#">설정</a>
                    <a class="dropdown-item" href="{% url 'mypg' %}">마이 페이지</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="#">찜한 상품
                    </a>
                  </div>
                </li>
                {%endif%}
                <li class="nav-item dropdown">
                  <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    지역 카테고리
                  </a>
                  <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                    <a class="dropdown-item" href="#">영등동</a>
                    <a class="dropdown-item" href="#">신동</a>
                    
                    <a class="dropdown-item" href="#">신용동
                    </a>
                  </div>
                </li>
                
              </ul>
             
              {% if request.user.is_authenticated %}
              <form class="form-inline" action="{% url 'logout' %}" method="get">
                <button class="btn btn-outline-success" type="submit">로그아웃</button>
              </form>
              {%else%}
              <form class="form-inline" action="{% url 'login' %}" method="get">
                <button class="btn btn-outline-success" type="submit">로그인</button>
              </form>
              <form class="form-inline" action="{% url 'register' %}" method="get">
                <button class="btn btn-outline-success" type="submit">회원가입</button>
              </form>
              {%endif%}
              
              
              <p>Current User: {{ request.user }}</p>
              <p>User Authenticated: {{ request.user.is_authenticated }}</p>
              
            
            </div>
        </nav>
           
           

    <!-- 메인 컨텐츠 -->
    <div class="container mt-4">
        <div class="row">
            <!-- 이미지 섹션 (모바일에서는 위에, 데스크탑에서는 오른쪽에 표시됨) -->
            <div class="col-12 d-md-none">
                <label for="productImage"></label>
                <img src="{{ product_image_url|default:'' }}" class="img-fluid" alt="상품 이미지" id="productImage">
            </div>

            <!-- 입력 폼 섹션 -->
            <div class="col-md-6">
                <h2>상품 등록</h2>
                <form method="POST" action="{% url 'product_registration' %}">  <!-- action 추가 -->
                    {% csrf_token %}
                    <div class="form-group">
                        <label for="productLink">링크 입력</label>
                        <input type="text" class="form-control" id="productLink" name="productLink" value="{{ product_link|default:'' }}" placeholder="상품 링크를 입력하세요">
                    </div>
                    <button type="submit" class="btn btn-primary">상품정보 가져오기</button>

                    <div class="form-group mt-3">
                        <label for="productName">상품명</label>
                        <input type="text" class="form-control" id="productName" name="productName" value="{{ product_name|default:'' }}" placeholder="상품명을 입력하세요">
                    </div>

                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label for="price">가격</label>
                            <input type="text" class="form-control" id="price" name="price" value="{{ product_price|default:'' }}" placeholder="가격을 입력하세요">
                        </div>
                        <div class="form-group col-md-6">
                            <label for="shippingFee">배송비</label>
                            <input type="text" class="form-control" id="shippingFee" name="shippingFee" value="{{ shipping_fee|default:'' }}" placeholder="배송비를 입력하세요" readonly>
                        </div>
                    </div>

                    <!-- 인원수 및 주소 입력 -->
                    <div class="form-group">
                        <label for="quantity">인원수</label>
                        <input type="number" class="form-control" id="quantity" min="1" max="4" value="1">
                    </div>
                    
                    <button type="submit" class="btn btn-primary mt-3">등록</button>
                </form>
            </div>

            <!-- 이미지 섹션 (데스크탑에서 오른쪽에 표시) -->
            <div class="col-md-6 d-none d-md-block">
                <label for="productImage">상품 이미지</label>
                <img src="{{ product_image_url|default:'' }}" class="img-fluid" alt="상품 이미지" id="productImage">
            </div>
        </div>
    </div>  
</body>
</html>
모든정보가 db로 넘어가게 코드 수정해줘
class Product(models.Model):
    product_link = models.URLField(max_length=200)
    product_name = models.CharField(max_length=100)
    product_price = models.DecimalField(max_digits=10, decimal_places=2)
    shipping_fee = models.DecimalField(max_digits=10, decimal_places=2)
    quantity = models.PositiveIntegerField()
    def __str__(self):
        return self.product_name