Reputation: 11
My model data for my website wont appear on new page when using slug and I am unsure as to why this is happening as I managed to get it to work with the previous page of the website but when I try to call it on my html page nothing will load now and I use the slug in the view to access the page.
Models.py
class Parasite(models.Model):
name = models.CharField(max_length=128, unique=True)
slug = models.SlugField(max_length=100, unique=True)
description = models.TextField(max_length=100000)
image = models.ImageField(upload_to='parasite_images', default='default/default.jpg', blank=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Parasite, self).save(*args, **kwargs)
def __str__(self):
return self.name
views.py
def view_parasite(request,parasite_name_slug):
context_dict = {}
try:
parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasites'] = parasite
except Parasite.DoesNotExist:
context_dict['parasites'] = None
return render(request, 'parasites_app/viewpara.html', context = context_dict)
viewpara.html
{% extends 'parasites_app/base.html' %}
{% load static %}
{% block content_block %}
{% for p in parasite %}
<h3>{{p.name}}</h3>
{% endfor %}
{% endblock %}
urls.py
urlpatterns = [
path('login/', views.user_login, name='login'),
path('logout/', views.user_logout, name='logout'),
path('admin/', admin.site.urls),
path('', views.public, name='public'),
path('public/', views.public, name='public'),
path('private/', views.logged_in_content, name='private'),
path('public/<slug:parasite_name_slug>/',views.view_parasite, name='view_parasite'),
path('<slug:post_name_slug>/', views.show_post, name='show_post'),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
Upvotes: 1
Views: 35
Reputation: 6368
First mistake - you are getting one Parasite
object (cause you use method get
) and you call it with plural name 'parasites'
:
parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasites'] = parasite
Second mistake - when you want to show it in template, you call for single parasite
, but you decided to name the key parasites
.
{% for p in parasite %}
Third mistake - don't use for
loop for one object, just call it.
Answer:
views.py
parasite = Parasite.objects.get(slug=parasite_name_slug)
context_dict['parasite'] = parasite
viewpara.html
{% block content_block %}
{{ parasite.name }}
{% endblock %}
Upvotes: 1