Как я могу получить доступ к template_context_processors? - PullRequest
0 голосов
/ 30 марта 2020

При разработке сайта для интернет-магазина я хочу получить доступ к количеству товаров, добавленных в корзину. Для этого я добавил template_context_processors в мои settings.py. Но это не показывает количество предметов. В чем может быть проблема здесь? Мои views.py:

def cart(request):
    try:
        the_id = request.session['cart_id']
    except:
        the_id = None
    if the_id:
        cart = Cart.objects.get(id=the_id)
        context = {"cart":cart}
    else:
        empty_message = "Your cart is empty, please keep shopping."
        context = {"empty": True, "empty_message": empty_message}

    template = 'shopping_cart/cart.html'
    return render(request, template, context)


def add_to_cart(request, slug):
    request.session.set_expiry(120000)
    try:
        the_id = request.session['cart_id']
    except:
        new_cart = Cart()
        new_cart.save()
        request.session['cart_id'] = new_cart.id
        the_id = new_cart.id

    cart = Cart.objects.get(id=the_id)
    try:
        product = Product.objects.get(slug=slug)
    except Product.DoesNotExist:
        raise Http404
    except:
        pass 
    if not product in cart.products.all():
        cart.products.add(product)
        messages.success(request, mark_safe("Product added to cart. Go to <a href='cart/'>cart</a>"))
        return redirect('myshop-home')
    else:
        cart.products.remove(product)
        messages.success(request, mark_safe("Product removed from cart"))


    new_total = 0.00
    for item in cart.products.all():
        new_total += float(item.price)

    request.session['items_total'] = cart.products.count()
    cart.total = new_total
    cart.save()

    return HttpResponseRedirect(reverse('cart'))

Затем я добавил эту строку кода в свою базу. html:

<a class="nav-item nav-link" href="{% url 'cart' %}">Cart {{ request.session.items_total }}</a>

Мои settings.py:

"""
Django settings for pyshop project.

Generated by 'django-admin startproject' using Django 3.0.3.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '9+!*d3rl=9h#6!eyuyio_^ux0y44ft&bzvi55+6_rp+b+(^b!x'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'shopping_cart.apps.ShoppingCartConfig',
    'products.apps.ProductsConfig',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

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',
]

ROOT_URLCONF = 'pyshop.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [
            os.path.join(BASE_DIR, 'templates')
        ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'pyshop.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.static',
    'django.contrib.messages.context_processors.messages',
)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/

STATIC_URL = '/static/'

1 Ответ

0 голосов
/ 30 марта 2020

Определите контекстный процессор в вашем проекте:

# my_project/carts/context_processors.py
def current_cart(request):
    return {
        'CURRENT_CART': Cart.objects.filter(id=request.session['cart_id']).first() if 'cart_id' in request.session else None
    }

Добавьте свою функцию в настройку TEMPLATE_CONTEXT_PROCESSORS

# settings.py
...
TEMPLATE_CONTEXT_PROCESSORS = (
    'carts.context_processors.current_cart',
    'django.contrib.auth.context_processors.auth',
    'django.core.context_processors.debug',
    'django.core.context_processors.i18n',
    'django.core.context_processors.request',
    'django.core.context_processors.static',
    'django.contrib.messages.context_processors.messages',
)

Используйте переменную в своем шаблоне

<a class="nav-item nav-link" href="{% url 'cart' %}">
    Cart {{ CURRENT_CART.products.count() }}
</a>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...