код выдает ошибку я не могу ее найти помогите пожалуйста найти ошибку

Рейтинг: 0Ответов: 0Опубликовано: 02.03.2023

введите сюда описание изображения введите сюда описание изображения view.py from django.shortcuts import render from django.http import FileResponse import json

    class Product:
        def __init__(self, category, name, color, size,  material, price):
            self.category = category
            self.name = name
            self.color = color
            self.size = size
            self.material = material
            self.price = price
    
        def to_dict(self):
            return {
                "category" :self.category,
                "name" :self.name,
                "color" :self.color,
                "size" :self.size,
                "price" :self.price,
            }
        
    products_list = [product_1, product_2, product_3]
    products_dict = [product.to_dict() for product in products_list]
    
    categories_dict = {}
    for product in products_dict:
        category = product["category"]
        if category not in categories_dict:
            categories_dict[category] = []
        categories_dict[category].append(product)
    
    def save_to_json(self, filename):
        with open(filename, "w") as fp:
            json.dump(self.__dict__, fp)
    
    product = Product("name", "price")
    product.save_to_json("product.json")
    
    import os
    project_dir = os.path.dirname(os.path.abspath(__file__))
    
    categories_images_dir = os.path.join(project_dir, 'categories_images')
    os.makedirs(categories_images_dir, exist_ok=True)
    
    categories_images = {}
    categories_images['category_1'] = os.path.join(categories_images_dir, 'category_1.jpg')
    categories_images['category_2'] = os.path.join(categories_images_dir, 'category_2.jpg')
    
    @app.route('/categories/<category>')
    def get_category_image(category):
        # Получить путь до картинки по названию категории
        image_path = categories_images.get(category)
        if image_path is None:
            abort(404)
    
        # Отправить картинку по пути
        return send_file(image_path)
    
    
    product.py
    class Product():
    
        def __init__(self, id, category, name, color, size,  material, price):
    
            self.id = int(id)
            self.category = str(category)
            self.name = str(name)
            self.color = str(color)
            self.size = int(size)
            self.material = int(material)
            self.price = int(price)
    
    shirt = Product(2311463489, "одежда", "футболка", "зеленая", 36, False, 1099)
    
    product_1 =Product(2311463489, "одежда", "футболка", "зеленая", 36, False, 1099)
    
    jeans = Product(2311189759, "одежда", "джинсы", "светло-серые", 34, False, 2799)
    
    dress = Product(2311238523, "одежда", "платье", "красное", 36, False, 2099)
    
    boots = Product(2316033002, "обувь", "ботинки", "черные", 39,  False, 3599)
    
    
    print(f"ID : {shirt.id}, Категория: {shirt.category}, Имя : {shirt.name},  Размер : {shirt.size}, Цвет : {shirt.color}, Материал : {shirt.material}, Цена : {shirt.price} рублей.")
    print(" ")
    print(f"ID : {jeans.id}, Категория: {jeans.category}, Имя : {jeans.name},  Размер : {jeans.size}, Цвет : {jeans.color}, Материал : {jeans.material}, Цена : {jeans.price} рублей.")
    print(" ")
    print(f"ID : {dress.id}, Категория: {dress.category}, Имя : {dress.name},  Размер : {dress.size}, Цвет : {dress.color}, Материал : {dress.material}, Цена : {dress.price} рублей.")
    print(" ")
    print(f"ID : {boots.id}, Категория: {boots.category}, Имя : {boots.name},  Размер : {boots.size}, Цвет : {boots.color}, Материал : {boots.material}, Цена : {boots.price} рублей.")
    print(" ")
    
    #Сортировка по количеству символов
    list = ['shirt', 'jeans', 'dress', 'boots']
    for x, y in enumerate(list):
        print(x, y)
    
    views.py[![введите сюда описание изображения][1]][1]
    from django.shortcuts import render
    from django.http import HttpResponse, HttpResponseRedirect.
    from django.urls import reverse
    from django.views.decorators.csrf import csrf_exempt
    # # Create your views here.
    class Product():
        __max_id = 1
        
        def __init__(self, category, name, color, size,  material, price):
            self.id = Product.__max_id
            self.category = str(category)
            self.name = str(name)
            self.color = str(color)
            self.size = int(size)
            self.material = int(material)
            self.price = int(price)
            Product.__max_id += 1
    
        def __str__(self):
            return (
                f"ID : {self.id}.\n"
                +f"Категория: {self.category}.\n"
                +f"Имя : {self.name}.\n"
                +f"Размер : {self.size}.\n"
                +f"Цвет : {self.color}.\n"
                +f"Цена : {self.price} рублей."
            )
        
    products = [Product ("одежда", "футболка", "зеленая", 36, False, 1099),
                Product( "одежда", "джинсы", "светло-серые", 34, False, 2799),
                Product( "одежда", "платье", "красное", 36, False, 2099),
                Product( "обувь", "ботинки", "черные", 39,  False, 3599)]
    
    @csrf_exempt
    def products_view(request: HttpResponse):
          if request.method == 'GET':
            category = request.GET.get("category", None)
            print(repr(category), repr(products[-1].category))
            return HttpResponse(",\n\n".join(str(product) for product in products
                                             if category is None
                                             or  category == product.category))
          
    
          if request.method == "POST":
            body = [element.strip() for element in
                    request.body.decode("UTF-8").split("\n")]
            
            products.append(Product(
                category = body[1],
                name = body[2],
                color =  body[3],
                size = int(body[4]),
                material = body[5],
                price = int(body[6])
            ))
    
            return HttpResponse(str(products[-1]), status=200)
          
          return HttpResponse(status=405)
    
    @csrf_exempt
    def product_view(request: HttpResponse, id: int):
        filtered = [product for product in products if product.id == id]
    
        if len(filtered) == 0:
            return HttpResponse(status=404)
        
        product = filtered[0]
    
        if request.method == "GET":
            if product.name == "":
                return HttpResponseRedirect(reverse("products"))
            
            return HttpResponse(str(product))
        
        return HttpResponse(status=405)

Ответы

Ответов пока нет.