【问题标题】:Django NoReverseMatch and wrong URL Pattern matching attemptDjango NoReverseMatch 和错误的 URL 模式匹配尝试
【发布时间】:2020-09-19 04:01:47
【问题描述】:

我是 Django 新手,正在尝试通过创建博客应用程序来学习。

现在我遇到了一个我无法解决的错误。我尝试了所有方法并将其与我正在遵循的教程进行比较,但它似乎是相同的,但对我来说它不起作用。

所以我的提要页面上列出了一些帖子,当我想单击帖子标题以访问 'post-detail' 页面时,我收到 NoReverseMatch 错误,因为 Django 以某种方式尝试与错误的 URL 模式匹配,即'user-feed',但我希望与'post-detail'匹配。

错误信息:

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 %} 

我的提要应用程序的 urls.py 如下所示:

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'),
]

我的 views.py 看起来像这样:

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

我的 models.py 如下所示:

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})

在发生此错误之前,我使用 django 管理页面删除了一些旧帖子。

【问题讨论】:

  • 表示post.author.username不存在,或者为空。

标签: python django


【解决方案1】:

我怀疑这行有问题:

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

很可能 post.author.username 没有签出,它是否试图访问您删除的帖子之一的作者?

【讨论】:

  • 谢谢!我不小心在目标 HTML 页面上写了 'objects.author.username' 而不是 'object.author.username' ... facepalm
猜你喜欢
  • 2020-11-22
  • 2023-03-29
  • 2023-03-10
  • 2017-10-07
  • 2017-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-18
相关资源
最近更新 更多