10
Сен
2021

AttributeError at /cart/ ‘NoneType’ object has no attribute ‘_base_manager’

Пишу интернет магазин на Django, возникают проблемы с корзиной. Вылетает вот такая вот ошибка.

Вот такая ошибка вылетает.

Html файл:

{% load static %}
<!DOCTYPE html>
<html lang="en">

<head>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <meta name="author" content="">

  <title>H-made Dolls</title>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" crossorigin="anonymous">

  <!-- Custom styles for this template -->

</head>
<style>
    body {
      padding-top: 56px;
    }
</style>
<body>

  <!-- Navigation -->
  <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
    <div class="container">
      <a class="navbar-brand" href="{% url 'base' %}">H-made Dolls</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label>
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="navbarResponsive">
        <ul class="navbar-nav ml-auto">
          <li class="nav-item">
            <a class="nav-link" href="{% url 'cart' %}">Корзина <span class="badge badge-danger">{{ cart.products.count }}</span></a>
          </li>
        </ul>
      </div>
    </div>
  </nav>

  <!-- Page Content -->
  <div class="container">

    <div class="row">

      <div class="col-lg-3 mt-5">
        <div class="list-group">
          {% for category in categories %}
          <a href="{{ category.url }}" class="list-group-item">{{ category.name }} ({{ category.count }})</a>
          {% endfor %}
        </div>

      </div>
      <!-- /.col-lg-3 -->

      <div class="col-lg-9">
        {% block content %}
        {% if messages %}
            {% for message in messages %}
              <div class="alert alert-success alert-dismissible fade show mt-3" role="alert">
                <strong>{{ message }}</strong>
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
            {% endfor %}
        {% endif %}
        <div id="carouselExampleIndicators" class="carousel slide my-4" data-ride="carousel">
        </div>

        <div class="row">
          {% for product in products %}
          <div class="col-lg-4 col-md-6 mb-4">
            <div class="card h-100">
              <a href="{{ product.get_absolute_url }}"><img class="card-img-top" src="{{ product.image.url }}" alt=""></a>
              <div class="card-body">
                <h4 class="card-title">
                  <a href="{{ product.get_absolute_url }}">{{ product.title }}</a>
                </h4>
                <h6>{{ product.description }}</h6>
                <h5>{{ product.price }} руб.</h5>
                <a href="{% url 'add_to_cart' ct_model=product.get_model_name slug=product.slug %}">
                  <button class="btn btn-danger">Добавить в корзину</button>
                </a>
              </div>
            </div>
          </div>
          {% endfor %}
        </div>
        <!-- /.row -->
      {% endblock content %}
      </div>
      <!-- /.col-lg-9 -->

    </div>
    <!-- /.row -->

  </div>
  <!-- /.container -->
  <!-- Bootstrap core JavaScript -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"  crossorigin="anonymous"></script>

</body>

</html>

urls.py:

from django.urls import path

from .views import (
    BaseView,
    ProductDetailView,
    CategoryDetailView,
    CartView,
    AddToCartView,
    DeleteFromCartView,
    ChangeQTYView,
    CheckoutView,
    MakeOrderView
)


urlpatterns = [
    path('', BaseView.as_view(), name='base'),
    path('products/<str:ct_model>/<str:slug>/', ProductDetailView.as_view(), name='product_detail'),
    path('category/<str:slug>/', CategoryDetailView.as_view(), name='category_detail'),
    path('cart/', CartView.as_view(), name='cart'),
    path('add-to-cart/<str:ct_model>/<str:slug>/', AddToCartView.as_view(), name='add_to_cart'),
    path('remove-from-cart/<str:ct_model>/<str:slug>/', DeleteFromCartView.as_view(), name='delete_from_cart'),
    path('change-qty/<str:ct_model>/<str:slug>/', ChangeQTYView.as_view(), name='change_qty'),
    path('checkout/', CheckoutView.as_view(), name='checkout'),
    path('make-order/', MakeOrderView.as_view(), name='make_order')
]

cart.html:

{% extends 'base.html' %}

{% block content %}
<h3 class="text-center mt-5 mb-5">Ваша корзина {% if not cart.products.count %}пуста{% endif %}</h3>
{% if messages %}
    {% for message in messages %}
      <div class="alert alert-success alert-dismissible fade show" role="alert">
        <strong>{{ message }}</strong>
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
    {% endfor %}
{% endif %}
{% if cart.products.count %}
<table class="table">
  <thead>
    <tr>
      <th scope="col">Наименование</th>
      <th scope="col">Изображение</th>
      <th scope="col">Цена</th>
      <th scope="col">Кол-во</th>
        <th scope="col">Общая цена</th>
      <th scope="col">Действие</th>
    </tr>
  </thead>
  <tbody>
    {% for item in cart.products.all %}
        <tr>
          <th scope="row">{{ item.content_object.title }}</th>
          <td class="w-25"><img src="{{ item.content_object.image.url }}" class="img-fluid"></td>
          <td>{{ item.content_object.price }} руб.</td>
          <td>
            <form action="{% url 'change_qty' ct_model=item.content_object.get_model_name slug=item.content_object.slug %}" method="POST">
              {% csrf_token %}
              <input type="number" class="form-control" name="qty" style="width: 70px;" min="1" value="{{ item.qty }}">
              <br>
              <input type="submit" class="btn btn-primary" value="Изменить кол-во">
            </form>
          </td>
            <td>{{ item.final_price }} руб.</td>
          <td>
            <a href="{% url 'delete_from_cart' ct_model=item.content_object.get_model_name slug=item.content_object.slug %}"><button class="btn btn-danger">Удалить из корзины</button></a>
          </td>
        </tr>
    {% endfor %}
        <tr>
          <td colspan="2"></td>
          <td>Итого:</td>
          <td>{{ cart.total_products }}</td>
          <td><strong>{{ cart.final_price }} руб.</strong></td>
          <td><a href="{% url 'checkout' %}"><button class="btn btn-primary">Перейти к оформлению</button></a></td>
        </tr>
  </tbody>
</table>
{% endif %}
{% endblock content %}

Traceback

Environment:


Request Method: GET
Request URL: http://localhost:8000/cart/

Django Version: 2.2.16
Python Version: 3.9.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'mainapp',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']


Template error:
In template C:\Users\Fake\Desktop\django3-ecommerce-master\mainapp\templates\base.html, error at line 31
   'NoneType' object has no attribute '_base_manager'
   21 :     body {
   22 :       padding-top: 56px;
   23 :     }
   24 : </style>
   25 : <body>
   26 : 
   27 :   <!-- Navigation -->
   28 :   <nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
   29 :     <div class="container">
   30 :       <a class="navbar-brand" href="{% url 'base' %}">H-made Dolls</a>
   31 :       <button class="navbar-toggler" type="button" data-toggle="collapse" data-target ="#navbarResponsive" aria-contr ols="navbarResponsive" aria-expanded="false" aria-label>
   32 :         <span class="navbar-toggler-icon"></span>
   33 :       </button>
   34 :       <div class="collapse navbar-collapse" id="navbarResponsive">
   35 :         <ul class="navbar-nav ml-auto">
   36 :           <li class="nav-item">
   37 :             <a class="nav-link" href="{% url 'cart' %}">Корзина <span class="badge badge-danger">{{ cart.products.count }}</span></a>
   38 :           </li>
   39 :         </ul>
   40 :       </div>
   41 :     </div>


Traceback:

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in _resolve_lookup
  829.                     current = current[bit]

During handling of the above exception ('CartProduct' object is not subscriptable), another exception occurred:

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response
  115.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\handlers\base.py" in _get_response
  113.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)

File "C:\Users\Fake\Desktop\django3-ecommerce-master\mainapp\mixins.py" in dispatch
  42.         return super().dispatch(request, *args, **kwargs)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\views\generic\base.py" in dispatch
  97.         return handler(request, *args, **kwargs)

File "C:\Users\Fake\Desktop\django3-ecommerce-master\mainapp\views.py" in get
  122.         return render(request, 'cart.html', context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\shortcuts.py" in render
  36.     content = loader.render_to_string(template_name, context, request, using=using)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py" in render_to_string
  62.     return template.render(context, request)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\backends\django.py" in render
  61.             return self.template.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render
  171.                     return self._render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py" in render
  150.             return compiled_parent._render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in _render
  163.         return self.nodelist.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader_tags.py" in render
  62.                 result = block.nodelist.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\defaulttags.py" in render
  309.                 return nodelist.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render
  937.                 bit = node.render_annotated(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\defaulttags.py" in render
  209.                     nodelist.append(node.render_annotated(context))

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render_annotated
  904.             return self.render(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in render
  987.             output = self.filter_expression.resolve(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in resolve
  671.                 obj = self.var.resolve(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in resolve
  796.             value = self._resolve_lookup(context)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py" in _resolve_lookup
  837.                         current = getattr(current, bit)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\contenttypes\fields.py" in __get__
  240.                 rel_obj = ct.get_object_for_this_type(pk=pk_val)

File "C:\Users\Fake\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\contenttypes\models.py" in get_object_for_this_type
  168.         return self.model_class()._base_manager.using(self._state.db).get(**kwargs)

Exception Type: AttributeError at /cart/
Exception Value: 'NoneType' object has no attribute '_base_manager'

PS. Пробовал убирать строчку, не помогает.

Источник: https://ru.stackoverflow.com/questions/1327141/attributeerror-at-cart-nonetype-object-has-no-attribute-base-manager

Тебе может это понравится...

Добавить комментарий