What are the default entries in a context dictionary, context[], from a View?

25 views
Skip to first unread message

Michael Starr

unread,
Dec 22, 2022, 6:05:34 PM12/22/22
to Django users
I am starting to understand context dictionaries, and I figured out from some Googling that the get_context_dictionary method belongs in a View, the one that you want to provide entries for its corresponding template.

My question is somewhat academic: Why can't I just use the context dictionary plan/vanilla " ", and if I can, what are the default entries labeled? If not, I understand how to add entries to them no problem.

Code would be something like what is shown at this tutorial.

Thank you very much.

Mike

Michael Starr

unread,
Dec 22, 2022, 8:17:34 PM12/22/22
to Django users
I got an answer for ListView here but I don't know if that's the same for all views. Probably not would be my guess.
Mike

Michael Starr

unread,
Dec 22, 2022, 8:23:21 PM12/22/22
to Django users
Here is my code so far:

models
from django.db import models
from django.utils.text import slugify

class Pet(models.Model):
    name = models.CharField(max_length=255)
    age = models.IntegerField()
    slug = models.SlugField(allow_unicode=True, max_length=100, unique=True, default="default_pet_slug")

    def __str__(self):
        return self.name

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super().save(*args, **kwargs)

    def get_absolute_url(self):
        return reverse("pet:pet_details", kwargs={"slug": self.slug})


views
from django.views.generic.detail import DetailView
from pet.models import Pet

class PetDetailView(DetailView):
    model = Pet
    template_name = "pet_profile.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        pets = Pet.objects
        for pet in pets:
            context[pet.name] = pet
        return context

home.html
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Pet Memorial</title>
  </head>
  <body>
    {% for pet in pets %}
      <a href="{% url 'pet_details' slug=pet.slug %}">Pet Profile: {{ pet }}</a>
    {% endfor %}
  </body>
</html>


I get no errors, but nothing shows up. I have verified that there is an entry in Pet ("Mocha").

Mike
Reply all
Reply to author
Forward
0 new messages