I have set a model including some attributes and can get the model by a slug in views.py. However, I can't render its attributes into the template. Did I miss something?
Model.py
class article(models.Model):
title = models.CharField(max_length=200)
content = RichTextUploadingField()
slug = models.SlugField(unique=True, max_length=200)
def __str__(self):
return self.title
Views.py
def post_details(request, slug):
details = get_object_or_404(article, slug=slug)
context = {
details: 'details'
}
return render(request, 'post_details.html', context)
Urls.py
from django.contrib import admin
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('<slug:slug>/', views.post_details, name='post_details')
]
I have set a URL to get the article model's data by slug in index.html
<h4 ><a href="{% url 'post_details' article.slug %}">{{ article.title }}</a></h4>
post_details.html
<h2>{{ details.slug }}</h2>
I can access this template by slug but can't get any attributes by using the 'details' tag
CodePudding user response:
You've got the key: value the wrong way around in your context
dict in views.py
:
context = {
details: 'details'
}
# should be:
context = {
'details': details
}
Your version has a dict with key of the actual model instance, pointing to a value of the string "details"
, which is the opposite of what you want :-)
it "works" (doesn't cause an error) because templates silently ignore missing keys/attributes when accessing context variables.
There's a special setting string_if_invalid
that you can set on your template configuration to make it more obvious when a var isn't present, although as it mentions, you can't really leave it enabled all the time since lots of other code expects this silent empty-string behaviour.