Представления на основе классов не отображают HTML в шаблоне - отсутствует ли контекст?

Я начал работать с представлениями на основе классов, но коды, которые я написал изначально, не отображаются в шаблоне, когда я использую представления на основе классов. Данные, которые находятся в файле note.title (см. шаблон), просто не отображаются, когда я использую представления на основе классов.

Когда я возвращаюсь к представлениям на основе функций и обновляю страницу, HTML-код в шаблоне отображается без проблем. Кто-нибудь может объяснить, что вызывает эту ошибку?

Я читал что-то о том, что контекст не был найден шаблоном, но я не очень понимаю, что это значит и как контекст решает эту проблему.

Заранее спасибо!

views.py

from multiprocessing import context
from django.shortcuts import render
import notes
from .models import Notes
from django.http import Http404
from django.views.generic import ListView, DetailView, CreateView


# Create your views here.

class NotesCreateView(CreateView):
    models = Notes
    fields = ["title", "text"]
    succes_url = "/smart/notes"

class NotesListView(ListView):
     model = Notes
     context_objects_name = "note"
     template_name = "notes/notes_list.html"
    
class NotesDetailView(DetailView):
     model = Notes
     context_object_name = "note"


# def list(request):
#      all_notes = Notes.objects.all()
#      context = {'notes': all_notes}
#      return render(request, 'notes/notes_list.html', context)

# def detail(request, pk):
#       try: 
#           note = Notes.objects.get(pk=pk)
#       except Notes.DoesNotExist:
#           raise Http404("This note doesn't exist")
#       context = {'note': note}
#       return render(request, 'notes/notes_detail.html', context)

urls.py

from django.urls import path
from . import views

app_name = "notesApp"

urlpatterns = [
     path('notes', views.NotesListView.as_view(), name="notes.list"),
     path('notes/<int:pk>', views.NotesDetailView.as_view(), name="notes.deta"),
     path("notes/new", views.NotesCreateView.as_view(), name="notes.view"),
    
    #  path('notes', views.list, name="notes.list"),
    #  path('notes/<int:pk>', views.detail, name="notes.deta"),
]

шаблон

{% extends 'base.html' %}

{% block content %}
    <h1 class="my-5">This are the notes:</h1>

    <div class="row row-cols3 g-2">
        {% for note in notes %}

        <div class="col">
            <div class="p-3 border">
                <a href="{% url 'notesApp:notes.deta' pk=note.id %}" class="text-dark text-decoration-non">
                <h3>{{notes.title}}</h3>
                </a>
                
                {{note.text|truncatechars:10}}
            </div>
        </div>
        
        {% endfor %}
    </div>

{% endblock %}

Вы должны использовать именно то, что задали в context_objects_name. Так, если вы хотите перебирать Notes объекты в цикле ListView, то вы должны установить представление в:

class NotesListView(ListView):
     model = Notes
     context_objects_name = "notes"  # PLURAL

Тогда в шаблоне оставьте все как есть. Возможно, вы захотите изменить {{notes.title}} на {{note.title}}, потому что он находится внутри цикла for.

Вернуться на верх