首页 > 解决方案 > 没有用户匹配给定的查询 Django

问题描述

尝试在博客应用程序中显示帖子详细信息模板时,出现错误No User matches a given query。在我的模型中,我继承自 User 模型。似乎有什么问题?

# Third party imports.
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils import timezone

class Post(models.Model):
    """
        Creates Model for a post in the database.
    """
    title = models.CharField(max_length=100)
    sub_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):
        """
            A string representation of the post model.
        """
        return self.title

    def get_absolute_url(self):
        """
            Creates the absolute url for a particular post.
        """
        return reverse('blog:post-detail', kwargs={'pk': self.pk})

视图.py

class PostDetailView(DetailView):
    """
        View for a post's details
    """
    model = Post
    template_name ='blog/post_detail.html'
    context_object_name = 'posts'
    paginate_by = 3


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

网址.py:

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

# Local application imports.
from . import views

# Specifies the app's name.
app_name = "blog"

urlpatterns = [
    path('', PostListView.as_view(), name='home'),  # url for post list.
    path('user/<str:username>/',
         UserPostListView.as_view(),
         name='user-posts'),  # url for specific user post.
    path('post/<int:pk>/',
         PostDetailView.as_view(),
         name='post-detail'),  # url for post detail.
    path('post/new/',
         PostCreateView.as_view(),
         name='post-create'),  # url to create new post.
    path('post/<int:pk>/update/',
         PostUpdateView.as_view(),
         name='post-update'),  # url to update post.
    path('post/<int:pk>/delete/',
         PostDeleteView.as_view(), name='post-delete'),  # url to delete post.
    path('about/', views.about, name='about'),  # url for about page.
]

主页.html

{% extends 'blog/base.html' %}
{% load static %}
{% block crumb %}
{% for post in posts %}
<div class="post-preview">
<a href="{% url 'blog:post-detail' post.id %}">
<h2 class="post-title">{{ post.title }}   </h2>
<h3 class="post-subtitle">{{ post.sub_title }}  </h3>
</a>

<p class="post-meta" style="font-weight: 300;"> Posted by 
  <a class="text-muted">{{post.author}} on {{ post.date_posted|date:"F d, Y" }}</a>
  
</p>

</div>
<hr class="my-4" />
{% endfor %}

{% endblock %}

post_detail.html

{% extends "blog/base.html" %}
{% block content %}
  <article class="media content-section">
    <img class="rounded-circle article-img"
         src="{{ object.author.profile.image.url }}">
    <div class="media-body">
      <div class="article-metadata">
        <a class="mr-2"
           href="{% url 'blog:user-posts' object.author.username %}">{{ object.author }}
        </a>
        <small class="text-muted">{{ object.date_posted|date:"F d, Y" }}</small>
        {% if object.author == user %}
          <div>
            <a class="btn btn-secondary btn-sm mt-1 mb-1"
               href="{% url 'blog:post-update' object.id %}">Update
            </a>
            <a class="btn btn-danger btn-sm mt-1 mb-1"
               href="{% url 'blog:post-delete' object.id %}">Delete
            </a>
          </div>
        {% endif %}
      </div>
      <h2 class="article-title">{{ object.title }}</h2>
      <p class="article-content">{{ object.content }}</p>
    </div>
  </article>
{% endblock content %}

标签: django

解决方案


有关与您遇到的错误没有直接关系的错误的一些注释。

  • 您正在使用 a DetailView(显示单个对象的详细信息),看起来您想要 a ListView(列出用户的帖子)。
    • context_object_name是复数形式,这意味着你确实想要一个事物列表。
    • paginate_by在 s 中无效DetailView,因为无法对单个对象视图进行分页。
  • 您的视图引用 a blog/post_detail.html,而您已粘贴 a home.html。哪一个?
  • 您说“在我的模型中,我从 User 模型继承。”,但看起来您不是在导入自定义 User 模型,而是在导入默认的from django.contrib.auth.models import User. 如果您确实使用的从 BaseUser(不是 User)继承的自定义用户模型,那么这也是错误的。

我想,错误本身(因为您没有向我们提供回溯)来自

user = get_object_or_404(User, username=self.kwargs.get('username'))

这意味着您没有传入<username>该视图的 URL,或者<username>您使用的不正确(并且没有这样的用户)。(你没有向我们展示你的urls.py,所以这只是一个猜测。)

(无论如何,详细视图的 URL 可能不是指用户名,而是帖子的唯一标识符。)


编辑

在对原始帖子进行编辑之后,问题get_queryset()在于 DetailView 中的 只是无关的(因为不需要按用户名过滤),因此可以将类简化为:

class PostDetailView(DetailView):
    model = Post
    template_name ='blog/post_detail.html'

推荐阅读