Class based views does not render HTML in template-Is context missing?
I started to work with class based views, but the codes that I've written initially does not render in the template when I use class based views. The data that is in note.title (see template) simply does not show up when I use class based views.
When I change back to function based views and refresh the page, the HTML code in the template shows up without any problems. Could someone explain what causes this error?
I've read something about context not been found by the template but I don't really understand what it means and how context resolves the issue.
Thanks in advance!
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"),
]
template
{% 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 %}
You have to use precisely what you set in context_objects_name
. So if you want to loop through Notes
objects in ListView
, then you have to set your view to:
class NotesListView(ListView):
model = Notes
context_objects_name = "notes" # PLURAL
Then in template leave everything as is. Well, maybe you want to change {{notes.title}}
to {{note.title}}
, because it is inside the for
loop.