.objects.all()查询在Django中不起作用

时间:2017-07-27 08:51:20

标签: python html django sqlite

我正在开发一个基于书籍信息的网站,我希望在HTML页面的“作者”表中显示所有作者。当我点击链接“authors”时,页面不会呈现,并且会显示错误“用户匹配查询不存在”。 (不要让我在这里发布图片)。 这是来自终端的追溯。

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>

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

非常感谢帮助。谢谢

2 个答案:

答案 0 :(得分:4)

/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'模式跟踪用户1}})。

修复网址格式后,追溯表明您的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():

答案 1 :(得分:3)

您向我们展示的代码似乎很好,但在您的代码中的某个地方,您可以使用以下代码:

User.objects.get(username=user_id)

由于您尝试将id与用户名匹配,因此无法找到任何内容,而get()找不到任何内容时会抛出异常。

您应该采取措施来捕捉错误,例如except User.DoesNotExists并确定您的情况。