【问题标题】:.objects.all() query not working in Django.objects.all() 查询在 Django 中不起作用
【发布时间】:2017-07-27 08:51:19
【问题描述】:

我正在开发一个基于书籍信息的网站,我想在 HTML 页面中显示“作者”表中的所有作者。当我单击链接“作者”时,该页面未呈现,并给出错误“用户匹配查询不存在”。 (不让我在这里张贴图片)。 这是来自终端的回溯。

Internal Server Error: /books/authors/
Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Python27\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Pallav\PycharmProjects\onlineBookStore\onlineBookStore\books\views.py", line 35, in follow_user
    user_to_be_followed = User.objects.get(username=username)
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 380, in get
    self.model._meta.object_name
DoesNotExist: User matching query does not exist.

我尝试在 python manage.py shell 中运行查询,它产生了正确的查询集。

我的urls.py 文件是:

app_name = 'books'

urlpatterns = [
    # /books/
    url(r'^$', views.IndexView.as_view(), name='index'),

    # /register/
    url(r'register/$', views.UserFormView.as_view(), name='register'),

    # /logout/
    url(r'logout/$', views.logout_user, name='logout'),

    # /login/
    url(r'login/$', views.login_user, name='login'),

    # /search/
    url(r'search/$', views.search, name='search'),

    # /add_book/
    url(r'search/(?P<isbn>[0-9]+)/add_book$', views.add_book, name='add_book'),

    # /books/<book_id>/
    url(r'^(?P<book_id>[0-9]+)/$', views.detail, name='detail'),

    # /books/favorite/
    url(r'^(?P<book_id>[0-9]+)/favorite/$', views.favorite, name='favorite'),

    # /books/rate/
    url(r'^(?P<book_id>[0-9]+)/rate/$', views.rate, name='rate'),

    # /books/review/
    url(r'^(?P<book_id>[0-9]+)/review/$', views.review, name='review'),

    # /books/borrow/
    url(r'^(?P<book_id>[0-9]+)/borrow/$', views.borrow, name='borrow'),

    # books/user_profile/
    url(r'user_profile/$', views.user_profile, name='user_profile'),

    # books/edit_profile
    url(r'edit_profile/$', views.edit_profile, name='edit_profile'),

    # books/login_btn
    url(r'login_btn/$', views.login_btn, name='login_btn'),

    # books/show_users
    url(r'show_users/$', views.show_users, name='show_users'),

    # books/<username>/
    url(r'^(?P<username>[a-z]*[A-Z]*[0-9]*)/$', views.follow_user, name='follow_user'),

    # books/authors/
    url(r'authors/$', views.authors, name='authors'),
]

我的视图功能是:

def authors(request):
    all_authors = Authors.objects.all()
    return render(request, 'books/authors.html', {'all_authors': all_authors})

def follow_user(request, username):
    user_following = request.user

    if user_following is not None:
        user_to_be_followed = User.objects.get(username=username)
        Follow.objects.add_follower(user_following, user_to_be_followed)
        return render(request, 'books/test.html')
    else:
        return render(request, 'books/registration_form.html')

我的 Html 页面 authors.html 是:

{% extends 'books/base.html' %}

{% block title %}All authors{% endblock %}
{% block body %}

    <div class="users-container container-fluid">

        <!-- Books -->
        <div class="row">
            {% if all_authors %}
                {% for author in all_authors %}

                    <div class="col-sm-4 col-lg-2">
                        <div class="thumbnail">
                            <h1>{{ author.name }}</h1>
                        </div>
                    </div>
                    <br>

                {% endfor %}
            {% else %}
                <h3>Currently no authors available</h3>
            {% endif %}
        </div>

    </div>

{% endblock %}

视图函数“follow_user”只是为了进入数据库,它没有与之关联的HTML页面。

test.html 是

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {% load friendshiptags %}


    <h1> {% following request.user %} </h1>

</body>
</html>

我访问了类似问题的不同链接,但没有一个能解决我的问题。链接1:objects.all() query not working 链接2:Django objects.all() empty query set, not empty in shell

非常感谢您的帮助。谢谢

【问题讨论】:

  • 请再次查看您的堆栈跟踪。您提供的视图不是导致问题的视图。在follow_user`文件“C:\Users\Pallav\PycharmProjects\onlineBookStore\onlineBookStore\books\views.py”第35行中调用user_to_be_followed = User.objects.get(username=user_id)时会出现问题。
  • 如您所见,您没有在函数中进行任何查询。您的问题肯定出在 urls.py 中。发布您的完整 urls.py 代码
  • 好吧,@alasdair 编辑的答案应该适合你。
  • 顺便说一句,当您关注/取消关注用户时,您应该使用发布请求而不是获取请求,因为您正在更改数据。进行更改后,通常的做法是重定向而不是呈现视图。
  • 注意!再次感谢:)

标签: python html django sqlite


【解决方案1】:

您对/books/authors/ 的请求正在由follow_user 视图处理,因为它们都匹配,并且follow_user 模式高于authors 模式。

# books/<username>/
url(r'^(?P<username>[a-z]*[A-Z]*[0-9]*)/$', views.follow_user, name='follow_user'),

# books/authors/
url(r'authors/$', views.authors, name='authors'),

您可以通过更改正则表达式以使其不会发生冲突来解决此问题,或者将authors 模式移动到follow_user 模式上方(注意这将阻止您使用username='authors' 关注用户)。

一旦您修复了 URL 模式,回溯表明您的 follow_user 视图中存在您应该修复的问题:

user_to_be_followed = User.objects.get(username=username)

如果用户有可能在数据库中不存在,那么您也需要处理这种可能性。你可以捕捉到异常:

try:
    user_to_be_followed = User.objects.get(username=username)
except User.DoesNotExist:
    user_to_be_followed = None

或者您可以使用get_object_or_404 快捷方式:

from django.shortcuts import get_object_or_404

user_to_be_followed = get_object_or_404(User, username=username)

最后注意以下检查不正确:

user_following = request.user 
if user_following is not None:
    ...

如果用户未登录,则request.user 将是匿名用户,而不是None。您应该在 Django 1.10+ 中检查 if request.user.is_authenticated:,或者在早期版本中检查 if request.user.is_authenticated():

【讨论】:

  • 作者模块不需要任何用户,也不需要对用户表进行查询。此外,作者表与用户表无关(阅读:foreign_key 等)。我不知道为什么回溯显示该声明。我将编辑我的问题以包含这些详细信息。另外,我在命名上犯了一个错误。 user_id 实际上是用户名。谢谢你,我会解决的。
  • 回溯显示错误发生的位置。如果代码不在您的 authors 视图中,则意味着 Django 没有运行作者视图。您的网址格式可能有错误(例如,缺少 $ 的正则表达式) - 您没有显示完整的网址,所以我无法确定。
  • 如果你改变了代码,你应该添加新的回溯——你不应该在回溯中有User.objects.get(username=user_id)
  • 非常感谢您的回复!有效。并对问题的无能框架感到抱歉。我是新来的。还在学习:)
  • 很高兴它成功了。随着您的练习越来越多,阅读回溯会变得更加容易,并且您将能够更快地查明问题:)
【解决方案2】:

您向我们展示的代码看起来不错,但在您的代码中的某处您有这行:

User.objects.get(username=user_id)

由于您尝试将 id 与用户名匹配,它不会找到任何东西,当 get() 找不到任何东西时,它会引发异常。

你应该做一些事情来捕捉错误,比如except User.DoesNotExists,当然要修复你的状况。

【讨论】:

    猜你喜欢
    • 2015-08-18
    • 2015-12-27
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-10
    • 2016-04-13
    相关资源
    最近更新 更多