简体   繁体   中英

How to fix No Reverse Match error in Django

I am having this error any time i want to view posts that belong to a group

NoReverseMatch at /groups/posts/in/python/
Reverse for 'user-posts' with keyword arguments '{'username': ''}' not found. 1 pattern(s) tried: ['user/(?P<username>[^/]+)$']

Following is my urls.py codes

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

app_name = 'posts'

urlpatterns = [
    path('', PostListView.as_view(), name="blog-home"),
    path('user/<str:username>', UserPostListView.as_view(), name="user-posts"),
    path('post/<int:pk>/', PostDetailView.as_view(), name="post-detail"),
    path("post/<int:pk>/", views.post_comment, name="comments"),
    path('post/new/', PostCreateView.as_view(), name="post-create"),
    path('post/<int:pk>/update', PostUpdateView.as_view(), name="post-update"),
    path('post/<int:pk>/delete', PostDeleteView.as_view(), name="post-delete"),
    path('about/', views.about, name="blog-about"),

]

The problem seems to be coming from my _posts.html file, but I cant resolve it.

here is the _posts.html codes

<div class="media">
    <h3 class="mr-5"><a href="{% url 'posts:user-posts' username=post.user.username %}">@{{ post.user.username }}</a></h3>
    <div class="media-body">
        <strong>{{ post.user.username }}</strong>
        <h5>{{ post.message_html|safe }}</h5>
            <time class="time"><a href="{% url 'posts:post-detail' username=post.user.username pk=post.pk %}">{{ post.created_at }}</a></time>
            {% if post.group %}
            <span class="group-name">in <a href="#">{{ post.group.name }}</a></span>
            {% endif %}
        </h5>

        <div class="media-footer">
            {% if user.is_authenticated and post.user == user and not hide_delete %}
                <a href="{% url 'posts:post-delete' pk=post.pk %}" title="delete" class="btn btn-simple">
                    <span class="fa fa-remove text-danger" aria-hidden="true"></span>
                    <span class="text-danger icon-label">Delete</span>
                </a>
            {% endif %}
        </div>
    </div>
</div>

Once I click on the group's list page to take me to posts associated with the group, I get the above error.

Someone said the username I am passing to the urls.py is empty, i cant figure out what is wrong with code from my views.py

from django.contrib import messages
from django.contrib.auth.mixins import (LoginRequiredMixin, UserPassesTestMixin)
from django.contrib.auth.models import User
from django.urls import reverse_lazy, reverse
from django.http import HttpResponseRedirect, Http404
from django.shortcuts import render, get_object_or_404, redirect
from django.views.generic import (ListView, DetailView, CreateView,
                                  UpdateView, DeleteView)

from .models import Post, Comment
from django.core.files.storage import FileSystemStorage
from .forms import CommentForm, PostForm
from . import models



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

def upload(request):
    if request.method == 'POST':
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return redirect('post_detail')
    else:
        form = PostForm()
    return render(request, 'blog/post_detail.html',
                  {'form': form })

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

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

    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

def post_comments(request, slug):
    template_name = 'blog/post_detail.html'
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.filter(active=True)
    new_comment = None
    # Comment posted
    if request.method == 'POST':
        comment_form = CommentForm(data=request.POST)
        if comment_form.is_valid():
            # Create Comment object but don't save to database yet
            new_comment = comment_form.save(commit=False)
            # Assign the current post to the comment
            new_comment.post = post
            # Save the comment to the database
            new_comment.save()
    else:
        comment_form = CommentForm()

    return render(request, template_name, {'post': post,
                                               'comments': comments,
                                               'new_comment': new_comment,
                                               'comment_form': comment_form})


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

    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
        return False

class PostDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
    model = Post
    success_url = reverse_lazy('blog-home')

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


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

There is nothing wrong with your urls.py and template. The problem is with '{'username': ''}' because username is empty it won't match with the regex( user/(?P<username>[^/]+)$ ). try to find out why username is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM