Django模板无法访问上下文,ListView开发遇阻求助(新手)
Hey there! As a Django newbie, working with class-based views like ListView can feel tricky at first—let’s break down the most common pitfalls that might be causing your problem, based on the code snippet you shared.
Common Issues & Fixes
1. Incorrect Inheritance Order (Critical!)
You mentioned using LoginRequiredMixin—Django requires mixins to be placed before the generic view in the inheritance chain. If you had it reversed (e.g., ListView, LoginRequiredMixin), the authentication check won’t work properly. Here’s the correct structure:
class StorageListView(LoginRequiredMixin, ListView): # Your view config here
2. Missing Required ListView Attributes
ListView needs to know what data to display. You’re likely missing one or more of these:
model: Directly specifies the model to fetch (simplest option)queryset: Use this if you need filtered data (e.g.,Storage.objects.filter(active=True))template_name: Optional, but if you don’t specify it, Django looks for a default template atstorage/storage_list.html(app name + model name +_list.html). If this template doesn’t exist, you’ll get a template error.
3. Unconfigured URL Mapping
Make sure your urls.py correctly maps to the view. Without this, accessing the view will throw a 404 error:
# In your app's urls.py from django.urls import path from .views import StorageListView urlpatterns = [ path('storages/', StorageListView.as_view(), name='storage-list'), ]
4. Authentication Redirect Issues
LoginRequiredMixin redirects unauthenticated users to the login page by default. If you haven’t set up your login URL (or it’s not matching Django’s default /accounts/login/), add this to your settings.py:
LOGIN_URL = '/your-login-path/' # Replace with your actual login route
Complete Working Example
Here’s a polished version of your view code with all necessary pieces:
from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.list import ListView from django.views.generic.detail import DetailView from Storage.models import Storage class StorageListView(LoginRequiredMixin, ListView): model = Storage # Tells Django to fetch all Storage objects context_object_name = 'storages' # Custom variable name for your template (instead of default `object_list`) template_name = 'storage/storage_list.html' # Path to your template # Optional: If you need a DetailView for individual Storage items class StorageDetailView(LoginRequiredMixin, DetailView): model = Storage template_name = 'storage/storage_detail.html'
Sample Template (storage/storage_list.html)
Create this template in your app’s templates/storage directory:
{% extends 'base.html' %} <!-- Extend your base template if you have one --> {% block content %} <h1>All Storage Items</h1> {% if storages %} <ul> {% for item in storages %} <li>{{ item.name }} <!-- Add other model fields as needed --></li> {% endfor %} </ul> {% else %} <p>No storage items found.</p> {% endif %} {% endblock %}
Final Checks
- Ensure your
Storagemodel is properly defined inStorage/models.pyand you’ve run migrations (python manage.py makemigrations+python manage.py migrate). - Test while logged in—since
LoginRequiredMixinblocks unauthenticated users, you’ll need a valid user account to see the view.
If you’re getting a specific error message (like a template not found, attribute error, or authentication redirect loop), share that detail and we can narrow it down further!
内容的提问来源于stack exchange,提问作者Gokhan Karahan

