简体   繁体   中英

Django NoReverseMatch and wrong URL Pattern matching attempt

I am new to Django and trying to learn by creating a Blog App.

Now I ran into an error I am not able to solve. I tried everything and compared it to the tutorial I am following but it seems to be the same but for me it is not working.

So I have some posts which are listed on my feed page and when I want to click on the post title to get to the 'post-detail' page I am getting a NoReverseMatch Error because Django somehow tries to match with a wrong URL pattern, which is 'user-feed' but instead I am expecting to match with 'post-detail' .

Error Message:

Reverse for 'user-feed' with arguments '('',)' not found. 2 pattern(s) tried: ['feed/user/(?P<username>[^/]+)/$', 'user/(?P<username>[^/]+)/$']

Feed.html:

{% for post in posts %}
        <article class="media content-section">
            <img class="rounded-circle article-img" src="{{ post.author.profile.image.url }}">
            <div class="media-body">
            <div class="article-metadata">
                <a class="mr-2" href="{% url 'user-feed' post.author.username %}">{{ post.author }}</a>
                <small class="text-muted">{{ post.date_posted|date:"d. F Y" }}</small>
            </div>
            <h2><a class="article-title" href="{% url 'post-detail' post.id %}">{{ post.title }}</a></h2>
            <p class="article-content">{{ post.content }}</p>
            </div>
        </article>
{% endfor %} 

My urls.py for my feed app looks as follows:

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

My views.py looks like this:

class PostListView(ListView):
    model = Post
    template_name = 'feed/feed.html' # Replaces the original template src which is <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

class UserPostListView(ListView):
    model = Post
    template_name = 'feed/user_feed.html' # Replaces the original template src which is <app>/<model>_<viewtype>.html
    context_object_name = 'posts'
    ordering = ['-date_posted']
    paginate_by = 10

    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(CreateView):
    model = Post
    fields = ['title', 'content']

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

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

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

    # Function to test whether the current user is the author of the post he wants to edit
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

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

    # Function to test whether the current user is the author of the post he wants to delete
    def test_func(self):
        post = self.get_object()
        if self.request.user == post.author:
            return True
        return False

My models.py looks as follows:

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    date_posted = models.DateTimeField(default=timezone.now)
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

Before this error occurred I deleted some old posts using the django admin page.

I suspect it has a problem with this line:

<a class="mr-2" href="{% url 'user-feed' post.author.username %}">{{ post.author }}</a>

Most likely the post.author.username is not checking out, is it trying to access the author of one of the posts you deleted?

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