DEV Community


Posted on • Updated on

Fix "None Type is not iterable " in Django

Error Message


According to the breakpoint debug, I found it's caused by the context processors that I had defined.

Comment it first.

        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates', os.path.join(BASE_DIR, 'templates')]
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                # 'food.context_processors.access_realtime_cart_count'
Enter fullscreen mode Exit fullscreen mode


Comment this line, the application turned into a normal state.

It seems that the context processor changed the context that login page needed.

We are in an unauthorized state when we enter the system for the first time. So we need to handle this situation.


The right way to declare a context processor is below:

### food/
from .models import OrderItem, Order

# the order item number of you current cart
def access_realtime_cart_count(request):
    if request.user.is_authenticated:
            active_order = Order.objects.get(user__username=request.user.username, status=1)
        except Order.DoesNotExist:
            newOrder = Order(user=request.user, total_price=0.0, status=1)
            active_order = newOrder
        cart_count = OrderItem.objects.filter(
        return {'realtimeCartCount': cart_count} # you can access the "cart_count" variable in any tempaltes of your projec
    else: # handle the unlogin 
        return {'realtimeCartCount': 0}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)