'Category' object is not iterable - python

I am new to programming
I have different categoriries in my django website, I created the model, view. but when I try to go to the localhost/category/categoryname, I get the error: "Category object is not iterable"
I appreciate your help in advance
#url.py
urlpatterns = [
path('', home, name='home'),
path('article/<slug:slug>', detail, name='detail'),
path('article', article, name='article'),
path('category/<slug:slug>', category, name='category')]
###############################################
#views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, JsonResponse, Http404
from .models import Article, Category
# Create your views here.
def home(request):
context = {
"articles": Article.objects.filter(status="Published")
}
return render(request, 'website/home.html', context)
def detail(request, slug):
context = {
"article": get_object_or_404(Article, slug=slug, status="Published")
}
return render(request, 'website/detail.html', context)
def article(request):
context = {
"articles": Article.objects.filter(status="Published"),
"category": Category.objects.filter(status=True)
}
return render(request, 'website/article.html', context)
def category(request, slug):
context = {
"category": get_object_or_404(Category, slug=slug, status=True)
}
return render(request, 'website/category.html', context)
###############################
#models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length=300, verbose_name="Category Topic")
slug = models.SlugField(max_length=100, unique=True, verbose_name="Category Address")
status = models.BooleanField(default=True, verbose_name="Do you want to show?")
position = models.IntegerField(verbose_name="position")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['position']
def __str__(self):
return self.title
class Article(models.Model):
STATUS_CHOICES = (
('Draft', 'Draft'),
('Published', 'Published')
)
title = models.CharField(max_length=300)
slug = models.SlugField(max_length=100, unique=True)
category = models.ManyToManyField(Category, verbose_name="Category", related_name="articles")
description = models.TextField()
thumbnail = models.ImageField(upload_to="images")
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10, choices=STATUS_CHOICES)
class Meta:
ordering = ['-publish']
def __str__(self):
return self.title
######################
#category.html
{% for article in category.articles.all %}
<article class="entry" data-aos="fade-up">
<div class="entry-img">
<img src="{{ article.thumbnail.url }}" alt="" class="img-fluid">
</div>
<h2 class="entry-title">
{{ article.title }}
</h2>
<div class="entry-meta">
<ul>
<li class="d-flex align-items-center"><i class="icofont-user"></i>
John Doe</li>
<li class="d-flex align-items-center"><i class="icofont-wall-clock"></i>
<time>{{ article.publish }}</time></li>
<li class="d-flex align-items-center"><i class="icofont-tags"></i>
<ul class="tags">
{% for cat in article.category.all %}
{{ cat.title }}
{% endfor %}
</ul>
</li>
<li class="d-flex align-items-center"><i class="icofont-comment"></i>
12 Comments</li>
</ul>
</div>
<div class="entry-content">
{{ article.description|truncatewords:30}}
<div class="read-more">
Read More
</div>
</div>
</article><!-- End blog entry -->
{% endfor %}

your code is shallow- please do this to retrieve category list
def get_queryset(self):category =
get_object_or_404(Category, slug=self.kwargs.get("slug"))
return Post.objects.filter(category_id=category).order_by("-created")
you can use this to retieve category by specific list
Article.objects.filter(post__category__contains='politics'),

I changed the view and the problem solved:
def category(request, slug):
cat = get_object_or_404(Category, slug=slug, status=True)
context = {
"category": cat.articles.all()
}
return render(request, 'website/category.html', context)

Related

ValueError at /category/economy/: Field 'id' expected a number but got 'economy'

I try to add new path and this happen "Field 'id' expected a number but got 'economy'."
in traceback the highlighted line is in the views.py file which i mentioned below.
category_posts = Post.objects.filter(category=cats)
I am sharing my files plz help me to get rid of the issue.
urls.py
urlpatterns = [
path('',views.allpost,name="allpost"),
path('search', views.search, name="search"),
path('contact/', views.contact, name="contact"),
path('success/', views.successView, name="success"),
path('category/<str:cats>/', views.CategoryView, name ="category"),
path('<int:blog_id>/',views.detail,name="detail"),
] + static(settings.MEDIA_URL,document_root = settings.MEDIA_ROOT)
here i used str:cats, yet it shows "Field 'id' expected a number but got 'economy'."
views.py
def CategoryView(request, cats): # here cats is same which mentioned in dynamic url.
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
"category_posts = Post.objects.filter(category=cats)" this line of code shows in traceback
models.py
from django.db import models
class Category(models.Model):
created_at = models.DateTimeField(auto_now_add=True, verbose_name="Created at")
title = models.CharField(max_length=255, verbose_name="Title")
parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=
True, null=True)
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
public_date = models.DateField(null=True)
public_time = models.TimeField(null=True,default="")
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="Category", null=True)
image = models.ImageField(upload_to='images/',null=True, blank=True)
body = models.TextField()
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
ordering = ['public_date']
def summary(self):
return self.body[:100]
def pub_date(self):
return self.public_date.strftime('%b %e,%y')
# to give layout for time and date
def __str__(self):
return self.title
categories.html
{% extends 'base.html' %}
{%block content%}
<h1> Category: {{ cats }} </h1>
{% for post in category_posts %}
<div class="container mt-3">
<div class="row mb-2">
<div class="col-md-6">
<div class="card flex-md-row mb-4 box-shadow h-md-250">
<div class="card-body d-flex flex-column align-items-start">
<strong class="d-inline-block mb-2 text-primary">{{ post.category }}</strong>
<h3 class="mb-0">
<a class="text-dark" href="{% url 'detail' post.id %}">{{post.title}}</a>
</h3>
<div class="mb-1 text-muted">{{ post.public_date }}</div>
<p class="card-text mb-auto">{{ post.summary }}</p>
Continue reading
</div>
<img class="card-img-right flex-auto d-none d-md-block" data-src="holder.js/200x250?theme=thumb" alt="Thumbnail [200x250]" style="width: 200px; height: 250px;" src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22200%22%20height%3D%22250%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20200%20250%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_182c981dfc3%20text%20%7B%20fill%3A%23eceeef%3Bfont-weight%3Abold%3Bfont-family%3AArial%2C%20Helvetica%2C%20Open%20Sans%2C%20sans-serif%2C%20monospace%3Bfont-size%3A13pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_182c981dfc3%22%3E%3Crect%20width%3D%22200%22%20height%3D%22250%22%20fill%3D%22%2355595c%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%2256.20000076293945%22%20y%3D%22131%22%3EThumbnail%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E" data-holder-rendered="true">
</div>
</div>
</div>
</div>
{% endfor %}
{% else %}
<h2>Sorry this page does not exist....</h2>
{% endif %}
{%endblock%}
I am confused it demands. can someone help me to solve it plz.
Its because you are querying it wrong:
So instaed of doing this:
# views.py
def CategoryView(request, cats): # here cats is same which mentioned in dynamic url.
category_posts = Post.objects.filter(category=cats)
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
Try something with this query. I'm supposing you want to query all the posts of a specific category that will be coming from your URL.
from django.shortcuts import get_object_or_404
def CategoryView(request, cats):
# method 1
category_posts = Post.objects.filter(category__title=cats)
# method 2
category = Category.objects.get(title=cats)
category_posts = category.Category.all() # here .Category is the related_name you used in your Post model
# method 3:
category = get_object_or_404(Category, title=cats) # will raise 404 if no category found with the given title
category_posts = category.Category.all()
return render(request, 'categories.html', {'cats':cats.title(), 'category_posts':category_posts})
PS: When you don't know what your ForeignKey related_name should be. Then go for the plural name of the model. Like in the current case:
# models.py
category = models.ForeignKey(Category, on_delete=models.CASCADE, verbose_name="posts", null=True)
This way we can query like this category_posts = category.posts.all()

Unable to Post comments to blog post with Django

I am creating a blog for a project and I am having problem getting my comments to post to the back end.
My code is as follows:
models.py
from django.contrib.auth.models import User
from products.models import Category
class Post(models.Model):
"""Model to create blog posts"""
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True)
title = models.CharField(max_length=250)
body = models.TextField(blank=True, null=True)
image = models.ImageField(blank=True, null=True)
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
class Comment(models.Model):
"""Model to handle user comments"""
author = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-created']
def __str__(self):
return self.body[0:50]
forms.py
from .models import Post, Comment
class PostForm(ModelForm):
"""
Form to allow site owner to create a new blog post
"""
class Meta:
model = Post
fields = ['category', 'title', 'body', 'image']
class CommentForm(ModelForm):
"""Form to handle user comments"""
class Meta:
model = Comment
fields = ('body',)
views.py
def add_comment(request):
"""Method to add comments to a blog post"""
post = get_object_or_404(Post, post_id)
comments = post.comments.all()
new_comment = None
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
template = 'blog/post_detail.html'
context = {
'post': post,
'comments': comments,
'new-comment': new_comment,
'comment_form': comment_form,
}
return render(request, template, context)
urls.py
from . import views
urlpatterns = [
path('', views.view_blog, name="blog"),
path('<int:post_id>/', views.post_detail, name="post_detail"),
path('add_post/', views.add_post, name="add_post"),
path('edit_post/<int:post_id>/', views.edit_post, name="edit_post"),
path('delete/<int:post_id>/', views.delete_post, name="delete_post"),
path('add_comment/', views.add_comment, name="add_comment"),
path('delete/comment/<int:comment_id>/', views.delete_comment, name="delete_comment"),
]
Could anyone see where I am going wrong please? I have been playing around and getting different type of name and value error and am not getting any further forward.
Current template
<div id="comment-input">
{% if request.user.is_authenticated %}
<form action="{% url 'add_comment' %}" method="POST">
{% csrf_token %}
<div class="w-100 mb-2">
{{ comment_form | crispy }}
<button class="form-control btn btn-black border border-black rounded-0" type="submit">Submit
</button>
</div>
{% endif %}
</div>
<div class="comment-wrapper">
{% for comment in post.comments.all %}
<div id="comment-details">
<div id="comment-author">
{{comment.author}} - {{comment.created|timesince}} ago
</div>
<div id="comment-body">
{{comment.body}}
</div>
</div>
<div id="delete-comment">
{% if request.user == comment.author %}
Delete Comment
{% endif %}
</div>
<hr>
{% endfor %}
</div>

My comments are not being displayed in a django blog

I am trying to add a comment section to add a comment section to my blog detail using django but when i run my server i get no error in the development server and the comments are not being displayed. I added the comments from my admin site.
The snippet of my code is below.
views.py
from .models import Post
from django.utils import timezone
from .forms import PostForm, CommentsForm
from django.contrib.auth.decorators import user_passes_test
# Create your views here.
def home(request):
return render (request, 'blogapp/home.html')
def blog_list(request):
post = Post.objects.order_by('-published_date')
context = {
'posts':post
}
return render(request, 'blogapp/blog_list.html', context)
def blog_detail(request, pk=None):
detail = Post.objects.get(pk=pk)
context = {
'detail': detail
}
return render(request, 'blogapp/blog_detail.html', context)
def add_post(request, pk=None):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid:
body = form.save(commit=False)
body.published_date = timezone.now()
body.save()
return redirect('blog_list')
form = PostForm()
else:
form = PostForm()
context = {
'form': form
}
return render(request, 'blogapp/add_post.html', context)
def add_comments(request, pk=None):
if request.method == "POST":
form = CommentsForm(request.POST)
if form.is_valid:
comment = form.save(commit=False)
comment.date_added = timezone.now()
comment.save()
return redirect('blog_detail')
form = CommentsForm()
else:
form = CommentsForm()
context = {
'form': form
}
return render(request, 'blogapp/add_comments.html', context)
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="homepage"),
path('blog/', views.blog_list, name="blog_list"),
path('blog/post/<int:pk>/', views.blog_detail, name="blog_detail"),
path('blog/add_post/', views.add_post, name="add_post"),
path('blog/add_comments/', views.add_comments, name="add_comments"),
]
forms.py
from django import forms
from .models import Post, Comments
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('author', 'title', 'post_description', 'image', 'image_description', 'body',)
class CommentsForm(forms.ModelForm):
class Meta:
model = Comments
fields = ('post', 'name', 'body',)
models.py
from django.db import models
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey('auth.user', on_delete=models.CASCADE)
title = models.CharField(max_length=300)
body = models.TextField()
post_description = models.CharField(max_length=500, blank=True, null=True)
image = models.ImageField(blank=True, null=True, upload_to="image/")
image_description = models.CharField(max_length=500, blank=True, null=True)
published_date = models.DateTimeField(default=timezone.now, blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Comments(models.Model):
post = models.ForeignKey('Post', related_name="comments", on_delete=models.CASCADE)
body = models.TextField()
name = models.CharField(max_length=300)
date_added = models.DateTimeField(default=timezone.now, blank=True, null=True)
def __str__(self):
return '%s - %s' % (self.post.title, self.name)
blog_detail.html
{% extends 'base.html' %}
{% load static %}
{% block content %}
<article>
<strong>
<h1><b>{{ detail.title }}</b></h1>
</strong>
<h3>POST AUTHOR: {{ detail.author }}</h3>
<h4><i>{{ detail.post_description }}</i></h4>
<h4>PUBLISHED:{{ detail.published_date }}</h4>
<p>
<hr>
{% if detail.image %}
<center>
<br>
<img src="{{ detail.image.url }}" width="1000" height="700">
<br><br>
<i>IMAGE DESCRIPTION: {{ detail.image_description }}</i>
</center>
{% endif %}
<hr>
<br><br><br>
{{ detail.body|linebreaksbr }}
</p>
<hr class="solid">
<h2>COMMENTS ...</h2>Add One
{% for comment in post.comments.all %}
<strong>
{{ comment.name }}-{{ comment.date_added }}
</strong>
{{ comment.body }}
{% endfor %}
</article>
{% endblock %}
add_comments.html
{% extends 'base.html' %}
{% block content %}
<article>
{% if user.is_authenticated %}
<h1>CREATE NEW BLOG POST.</h1>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">ADD COMMENT</button>
<input type="hidden" name="next" value="{% url 'blog_detail' pk=post.pk %}"/>
</form>
{% else %}
<h2>Login HERE to add comments.</h2>
{% endif %}
</article>
{% endblock %}
in your template you use
{% for comment in post.comments.all %}
but in template context there is no post variable
you should use {% for comment in detail.comments.all %}

Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P<name>[^/]+)$']

My question is about redirection again to a /topics/ page where all entries for topic are located. When I end an entry this code and reload tab than showing this error is occured as below:
Reverse for 'topic' with arguments '('',)' not found. 1 pattern(s) tried: ['topic/(?P[^/]+)$']
how can i solved this?
at views.py
from django.shortcuts import render, HttpResponse
from django.views.generic.base import View
from .models import author, catagory, article
# Create your views here.
class HomeView(View):
def get(self, request, *args, **kwargs):
post = article.objects.all()
context = {
"post":post
}
return render (request, 'index.html', context)
def getauthor(request, name):
return render (request, 'profile.html')
def getsingle(request, id):
return render (request, 'single.html')
def getTopic(request, name):
return render (request, 'category.html')
at urls.py
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.HomeView.as_view(), name = 'home'),
#path('about/', views.AboutView.as_view(), name = 'about'),
path('author/<name>', views.getauthor, name = 'author'),
path('article/<int:id>', views.getsingle, name = 'single_post'),
path('topic/<name>/', views.getTopic, name = 'topic'),
]
urlpatterns+= static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
at index.html
{% extends "base.html" %}
{% load static %}
{% block title %} Welcome to my django templates {% endblock %}
{% block content %}
{% for p in post %}
<article class="col-lg-3 col-md-3 col-sm-3 col-xs-6 col-xxs-12 animate-box">
<figure>
<img src="{{ p.image.url }}" alt="Image" class="img-responsive">
</figure>
<span class="fh5co-meta">{{ p.category.name }}</span>
<h2 class="fh5co-article-title">{{ p.title }}</h2>
<span class="fh5co-meta fh5co-date">{{ p.posted_on }}</span>
</article>
{% endfor %}
{% endblock %}
Modles.py are
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class author(models.Model):
name = models.ForeignKey(User, on_delete = models.CASCADE, related_name='blog_posts')
details = models.TextField()
def __str__(self):
return self.name.username
class catagory(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class article(models.Model):
article_author = models.ForeignKey(author, on_delete = models.CASCADE, related_name='blog_posts')
title = models.CharField(max_length=200)
body = models.TextField()
image = models.FileField()
posted_on = models.DateTimeField (auto_now= False, auto_now_add= True)
updated_on = models.DateTimeField (auto_now= True, auto_now_add= False)
catagory = models.ForeignKey(catagory, on_delete = models.CASCADE)
def __str__(self):
return self.title

Reverse for 'detail' with keyword arguments '{'id': 5}' not found. 1 pattern(s) tried: ['posts/(?P<slug>[\\w-]+)/$']

I'm super stuck with NoReverseMatch at /posts/ error. Maybe I am overlooking something small or maybe this issue is much bigger than where I am digging.
http://imgur.com/nlyMi9V
Error message when models.py is like this:
def get_absolute_url(self):
#return reverse("detail", kwargs={ "slug": self.slug })
return reverse("posts:detail", kwargs={ "slug": self.slug })
http://imgur.com/a/RilrB
Error message when models.py is like this:
def get_absolute_url(self):
return reverse("detail", kwargs={ "slug": self.slug })
#return reverse("posts:detail", kwargs={ "slug": self.slug })
models.py
#from _future_ import __unicode__literals
from django.db import models
from django.core.urlresolvers import reverse
from django.db.models.signals import pre_save
from django.utils.text import slugify
# Create your models here.
# MVC Models Views Controller
def upload_location(instance, filename):
# filebase, extension = filename.spilt(".")
# return "%s/%s.%s" %(instance.id, instance.id, filename)
return "%s/%s" %(instance.id, filename)
class Post(models.Model):
title = models.CharField(max_length=120)
slug = models.SlugField(unique=True)
image = models.ImageField(upload_to=upload_location,
null=True,
blank=True,
width_field="width_field",
height_field="height_field")
height_field = models.IntegerField(default=0)
width_field = models.IntegerField(default=0)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
def get_absolute_url(self):
#return reverse("detail", kwargs={ "slug": self.slug })
return reverse("posts:detail", kwargs={ "slug": self.slug })
class Meta:
ordering = ["-timestamp", "-updated"]
def create_slug(instance, new_slug=None):
slug = slugify(instance.title)
if new_slug is not None:
slug = new_slug
qs = Post.objects.filter(slug=slug).order_by("-id")
exists = qs.exists()
if exists:
new_slug = "%s-%s" %(slug, qs.first().id)
return create_slug(instance, new_slug=new_slug)
return slug
def pre_save_post_receiver(sender, instance, *args, **kwargs):
if not instance.slug:
instance.slug = create_slug(instance)
pre_save.connect(pre_save_post_receiver, sender=Post)
views.py
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect
from .forms import PostForm
# Create your views here.
from .models import Post
def post_create(request):
form = PostForm(request.POST or None, request.FILES or None,)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "Successfully Created!")
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"form": form,
}
return render(request, "post_form.html", context)
def post_detail(request, slug=None):
#instant = Post.objects.get(id=0)
instance = get_object_or_404(Post, slug=slug)
context = {
"title": instance.title,
"instance": instance,
}
return render(request, "post_detail.html", context)
def post_list(request):
queryset_list = Post.objects.all() #.order_by("-timestamp")
paginator = Paginator(queryset_list, 5) # Show 5 contacts per page
page_request_var = "page"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
queryset = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
queryset = paginator.page(paginator.num_pages)
context = {
"object_list": queryset,
"title": "List",
"page_request_var": page_request_var
}
return render(request, "post_list.html", context)
#return HttpResponse("<h1>List</h1>")
def post_update(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
form = PostForm(request.POST or None, request.FILES or None, instance=instance)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
# message success
messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
return HttpResponseRedirect(instance.get_absolute_url())
context = {
"title": instance.title,
"instance": instance,
"form":form,
}
return render(request, "post_form.html", context)
def post_delete(request, slug=None):
instance = get_object_or_404(Post, slug=slug)
instance.delete()
messages.success(request, "Successfully deleted!")
return redirect("posts:list")
urls.py
from django.conf.urls import url
from django.contrib import admin
from . import views
# from .views import (
# post_list,
# post_create,
# post_detail,
# post_update,
# post_delete,
# )
# video: https://www.youtube.com/watch?annotation_id=annotation_3160187747&feature=iv&index=14&list=PLEsfXFp6DpzQFqfCur9CJ4QnKQTVXUsRy&src_vid=nw3R2TXlkwY&v=1KuyH8JVn6A
# shows a different solution here for version 1.10
urlpatterns = [
#url(r'^$', views.post_home),
# url(r'^$', views.post_list, name='list'),
# url(r'^create/', views.post_create), #name='create'
# url(r'^(?P<slug>[\w-]+)/', views.post_detail, name='detail'),
# url(r'^(?P<slug>[\w-]+)/edit/', views.post_update, name='update'),
# url(r'^(?P<slug>[\w-]+)/delete/', views.post_delete),
url(r'^$', views.post_list, name='list'),
url(r'^create/$', views.post_create, name='create'),
url(r'^(?P<slug>[\w-]+)/$', views.post_detail, name='detail'),
url(r'^(?P<slug>[\w-]+)/edit/$', views.post_update, name='update'),
url(r'^(?P<slug>[\w-]+)/delete/$', views.post_delete),
# url(r'^$', posts.views.post_home),
# url(r'^create/', home_create),
# url(r'^list/', home_list),
# url(r'^detail/', home_detail),
# url(r'^update/', home_update),
# url(r'^delete/', home_delete),
# url(r'^posts/$', "<appname>.views.<function_name>"),
]
post_list.py
{% extends "base.html" %}
{% block head_title %}
{{ instance.title }} | {{ block.super }}
{% endblock head_title %}
{% block content %}
<div class="row justify-content-md-center">
<div class='col-md-8'>
<h1>{{title}}</h1>
</div>
{% for obj in object_list %}
<div class='col-md-8 pt-3'>
<div class="card" style="min-width: 20rem;">
{% if obj.image %}
<img src="{{ obj.image.url }}" class="card-img-top">
{% endif %}
<div class="card-body">
<h4 class="card-title">
<a href='{{ obj.get_absolute_url }}'>{{ obj.title }}</a>
<small>{{ obj.timestamp|timesince }} ago</small>
</h4>
<p class="card-text">{{ obj.content|linebreaks|truncatechars:120 }}</p>
<p class="card-text">{{ obj.updated }}</p>
<p class="card-text">{{ obj.id }}</p>
<!-- <a href='{% url "posts:detail" id=obj.id %}'>{{ obj.title }}</a><br/> -->
View
</div>
</div>
</div>
{% endfor %}
<div class='col-md-8'>
<div class="pagination">
<span class="step-links">
{% if object_list.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ object_list.number }} of {{ object_list.paginator.num_pages }}.
</span>
{% if object_list.has_next %}
next
{% endif %}
</span>
</div>
</div>
</div>
{% endblock content %}
The error is coming from this line
<!-- <a href='{% url "posts:detail" id=obj.id %}'>{{ obj.title }}</a><br/> -->
<!-- is an html comment, so Django still tries to reverse the url when it renders the template.
You can either remove the line entirely, change it to a Django comment {# ... #}, or change it to use the slug instead of id.

Categories