Blog app Error: NoReverseMatch at /post/14/

269 views
Skip to first unread message

Robert CR

unread,
Oct 12, 2018, 1:44:22 AM10/12/18
to Django users

I am making a blog app for my django website. Right now i'm making a comment feature, but when i try to view a post and the posts comments i get an error.

The Error

Udklip.PNG


Robert CR

unread,
Oct 12, 2018, 1:50:02 AM10/12/18
to Django users
I think it has something to do with my urls.py and views.py

urls.py
from django.urls import path
from .views import (
   
PostListView,
   
PostDetailView,
   
PostCreateView,
   
PostUpdateView,
   
PostDeleteView,
   
UserPostListView,
   
UserProfileListView,
   
UserProfilePostListView
)
from . import views


urlpatterns
= [
    path
('', PostListView.as_view(), name='blog-home'),
    path
('user/<str:username>/', UserProfileListView.as_view(), name='user-profile' ),
    path
('user/<str:username>/posts/', UserPostListView.as_view(), name='user-posts'),
    path
('user/<str:username>/posts/view/', UserProfilePostListView.as_view(), name='user-posts-view'),
    path
('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path
('post/<int:pk>/comment/', views.add_comment, name='add-comment'),
    path
('post/new', PostCreateView.as_view(), name='post-create'),
    path
('post/<int:pk>/edit/', PostUpdateView.as_view(), name='post-update'),
    path
('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
    path
('about/', views.about, name='blog-about')
]

views.py
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.models import User
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from .models import Post


def home(request):
    context = {
        'posts': Post.objects.all()
    }
    return render(request, 'blog/home.html', context)

def upsite(request):
    context = {
        'uposts': UPost.objects.all()
    }


class PostListView(ListView):
    model = Post
    template_name = 'blog/home.html'
    context_object_name = 'posts'
    ordering =['-date_posted']
    paginate_by = 5


class UserPostListView(ListView):
    model = Post
    template_name = 'blog/user_posts.html'
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

class UserProfileListView(ListView):
    model = Post
    template_name = 'blog/user_profile.html'
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

class UserProfilePostListView(ListView):
    model = Post
    template_name = 'blog/user_profile_posts.html'
    context_object_name = 'posts'
    paginate_by = 5

    def get_queryset(self):
        user = get_object_or_404(User, username=self.kwargs.get('username'))
        return Post.objects.filter(author=user).order_by('-date_posted')

class PostDetailView(DetailView):
    model = Post

class PostCreateView(LoginRequiredMixin, CreateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
    model = Post
    fields = ['title', 'content']

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super().form_valid(form)

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        else:
            return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = '/'

    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        else:
            return False

def about(request):
    return render(request, 'blog/about.html', {'title': 'About'})

def add_comment(request, slug):
    post = get_object_or_404(Post, slug=slug)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = CommentForm()
    template = 'blog/add-comment.html'
    context = {
        'form': form
    }
    return render(request, template, context)





Manjunath

unread,
Oct 12, 2018, 1:57:23 AM10/12/18
to Django users
Please provide snapshot of your template file as well as project's urls.py file.

Robert CR

unread,
Oct 12, 2018, 2:30:03 AM10/12/18
to Django users
here is the template file.

add_comment.html
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
  <div class="content-section">
    <form method="POST">
      {% csrf_token %}
        <fieldset class="form-group">
          <legend class="border-bottom mb-4">Comment</legend>
          {{ form|crispy }}
        </fieldset>
        <div class="form-group">
          <button class="btn btn-outline-warning" type="submit">Post Comment!</button>
        </div>
    </form>
  </div>
{% endblock content %}



Manjunath

unread,
Oct 12, 2018, 2:32:41 AM10/12/18
to Django users
Try adding for action to your add_comment url  then submit the form.
I guess currently form is getting submitted in the same page.

Glen D souza

unread,
Oct 12, 2018, 2:36:24 AM10/12/18
to django...@googlegroups.com
Hi,

Try after name-spacing url patterns i.e 

app_name = 'blog'

urlpatterns = [
    path
('', PostListView.as_view(), name='blog-home'),
    path
('user/<str:username>/', UserProfileListView.as_view(), name='user-profile' ),
    path
('user/<str:username>/posts/', UserPostListView.as_view(), name='user-posts'),
    path
('user/<str:username>/posts/view/', UserProfilePostListView.as_view(), name='user-posts-view'),
    path
('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path
('post/<int:pk>/comment/', views.add_comment, name='add-comment'),
    path
('post/new', PostCreateView.as_view(), name='post-create'),
    path
('post/<int:pk>/edit/', PostUpdateView.as_view(), name='post-update'),
    path
('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
    path
('about/', views.about, name='blog-about')
]


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/aeaadfcb-38b7-4db2-9921-1c8c2485fd5e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

daniel main

unread,
Oct 12, 2018, 2:58:52 AM10/12/18
to django...@googlegroups.com
Hello, 
Have you tried adding an app_name = 'your_app_name' in the URLs.py file?
Thanks

To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Robert CR

unread,
Oct 12, 2018, 3:06:10 AM10/12/18
to Django users
i fixed the error, thanks. But there is already a new one when i try to add a comment. D:

Udklip.PNG


Glen D souza

unread,
Oct 12, 2018, 3:20:20 AM10/12/18
to django...@googlegroups.com
try renaming path('post/<int:pk>/comment/', views.add_comment, name='add-comment'),

to path('post/<int:slug>/comment/', views.add_comment, name='add-comment'),

On Fri, 12 Oct 2018 at 12:36, Robert CR <robert...@gmail.com> wrote:
i fixed the error, thanks. But there is already a new one when i try to add a comment. D:

Udklip.PNG


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Robert CR

unread,
Oct 12, 2018, 3:26:27 AM10/12/18
to Django users
If i do that i get another error:

Udklip2.PNG


Glen D souza

unread,
Oct 12, 2018, 3:34:57 AM10/12/18
to django...@googlegroups.com

def add_comment(request, slug):
    post = get_object_or_404(Post, slug=slug)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = CommentForm()
    template = 'blog/add-comment.html'
    context = {
        'form': form
    }
    return render(request, template, context)

Check this view, it has an argument called slug and from your url you are passing parameter to that slug argument i.e path('post/<int:slug>/comment/', views.add_comment, name='add-comment')
In this case slug field will contain the id of the post i believe,

If you check this post = get_object_or_404(Post, slug=slug), slug field contains the id but your post model does not an attribute called slug so what you should really do is
post = get_object_or_404(Post, id=slug) or you can rename the url as path('post/<int:id>/comment/', views.add_comment, name='add-comment') and your view as 
def add_comment(request, id):
    post = get_object_or_404(Post, id=id)
    if request.method == 'POST':
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = post
            comment.save()
            return redirect('blog:post_detail', slug=post.slug)
    else:
        form = CommentForm()
    template = 'blog/add-comment.html'
    context = {
        'form': form
    }
    return render(request, template, context)
On Fri, 12 Oct 2018 at 12:56, Robert CR <robert...@gmail.com> wrote:
If i do that i get another error:

Udklip2.PNG


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

daniel main

unread,
Oct 12, 2018, 3:44:54 AM10/12/18
to django...@googlegroups.com
Use id instead of pk

To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.

To post to this group, send email to django...@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.

Robert CR

unread,
Oct 12, 2018, 3:56:00 AM10/12/18
to Django users
then a new error pops up:

Udklip3.PNG

Robert CR

unread,
Oct 12, 2018, 5:15:33 AM10/12/18
to Django users
is it because i have forgotten to import CommentForm?
Reply all
Reply to author
Forward
0 new messages