首页 > 解决方案 > 为什么我在这个 Django 应用程序中获得“NoReverseMatch at /catalog/borrowed/”错误?

问题描述

我是 Python 和 Django 的新手,我发现在尝试实现与如何在 Django 框架中处理用户\组和权限相关的 Mozilla Django 教程中显示的内容时遇到了一些困难:https ://developer.mozilla.org/it /docs/Learn/服务器端/Django/Authentication

我正在按照本教程中说明的步骤进行操作。

首先,通过 Django 管理面板,我创建了两组用户:

在此处输入图像描述

然后我创建了两个用户,将第一个用户放入Librarian组,将第二个用户放入Library Members组:

在此处输入图像描述

然后按照前面的教程,我处理了与用户(属于图书馆成员组的用户)借阅的书籍列表相关的模型\视图。

所以在我的catalog/models.py文件中,我定义了这个BookInstance模型类:

import uuid  # Required for unique book instances
from datetime import date

from django.contrib.auth.models import User  # Required to assign User as a borrower


class BookInstance(models.Model):
    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
                          help_text="Unique ID for this particular book across whole library")
    book = models.ForeignKey('Book', on_delete=models.SET_NULL, null=True)
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)

    @property
    def is_overdue(self):
        if self.due_back and date.today() > self.due_back:
            return True
        return False

    LOAN_STATUS = (
        ('d', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='d',
        help_text='Book availability')


    class Meta:
        ordering = ['due_back']
        permissions = (("can_mark_returned", "Set book as returned"),)

    def __str__(self):
        """String for representing the Model object."""
        return '{0} ({1})'.format(self.id, self.book.title)

如您所见,此模型类包含:

borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)

通过ForeignKey将BookInstance对象绑定到 User 。

如您所见,我还在此模型上定义了can_mark_returned权限。

然后在我的/catalog/view.py文件中,我定义了这个只能由图书馆员组中的用户访问的视图(设置了以前的can_mark_returned权限):

class LoanedBooksAllListView(PermissionRequiredMixin, generic.ListView):
    """Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission."""
    model = BookInstance
    permission_required = 'catalog.can_mark_returned'
    template_name = 'catalog/bookinstance_list_borrowed_all.html'
    paginate_by = 10

    def get_queryset(self):
        return BookInstance.objects.filter(status__exact='o').order_by('due_back')

在此视图的catalog/bookinstance_list_borrowed_all.html模板代码之后:

{% extends "base_generic.html" %}

{% block content %}
    <h1>All Borrowed Books</h1>

    {% if bookinstance_list %}
    <ul>

      {% for bookinst in bookinstance_list %} 
      <li class="{% if bookinst.is_overdue %}text-danger{% endif %}">
        <a href="{% url 'book-detail' bookinst.book.pk %}">{{bookinst.book.title}}</a> ({{ bookinst.due_back }}) {% if user.is_staff %}- {{ bookinst.borrower }}{% endif %} {% if perms.catalog.can_mark_returned %}- <a href="{% url 'renew-book-librarian' bookinst.id %}">Renew</a>  {% endif %}
      </li>
      {% endfor %}
    </ul>

    {% else %}
      <p>There are no books borrowed.</p>
    {% endif %}       
{% endblock %}

然后进入/catalog/urls.py文件,我定义了这个部分:

urlpatterns += [
    path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
    path(r'borrowed/', views.LoanedBooksAllListView.as_view(), name='all-borrowed'),  # Added for challenge
]

包含我对此页面感兴趣的所有借用路径。

注意:我从 Mozilla 教程 GitHub 复制并粘贴它,我不明白为什么它将这个r字符放在“借用”路径的前面,为什么?这里是 GitHub 文件链接: https ://github.com/mdn/django-locallibrary-tutorial/blob/master/catalog/urls.py

然后,从管理面板,我将此权限授予图书管理员

在此处输入图像描述

之后,我执行了迁移,我启动了我的 Django 应用程序,并使用属于该Librarian用户组的用户登录。所以我尝试使用以下 URL 访问与上一个视图相关的页面:http://localhost:8000/catalog/borrowed/

但现在我得到了这个错误页面:

NoReverseMatch at /catalog/borrowed/
Reverse for 'renew-book-librarian' not found. 'renew-book-librarian' is not a valid view function or pattern name.
Request Method: GET
Request URL:    http://localhost:8000/catalog/borrowed/
Django Version: 3.1.4
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'renew-book-librarian' not found. 'renew-book-librarian' is not a valid view function or pattern name.
Exception Location: /home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix
Python Executable:  /home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/bin/python3
Python Version: 3.8.5
Python Path:    
['/home/andrea/Documenti/Python-WS/django_projects/locallibrary',
 '/usr/lib/python38.zip',
 '/usr/lib/python3.8',
 '/usr/lib/python3.8/lib-dynload',
 '/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages']
Server time:    Thu, 31 Dec 2020 11:08:18 +0100
Error during template rendering
In template /home/andrea/Documenti/Python-WS/django_projects/locallibrary/catalog/templates/base_generic.html, error at line 0

Reverse for 'renew-book-librarian' not found. 'renew-book-librarian' is not a valid view function or pattern name.
1   <!DOCTYPE html>
2   <html lang="en">
3   <head>
4     {% block title %}<title>Local Library</title>{% endblock %}
5     <meta charset="utf-8">
6     <meta name="viewport" content="width=device-width, initial-scale=1">
7     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
8     <!-- Add additional CSS in static file -->
9     {% load static %}
10    <link rel="stylesheet" href="{% static 'css/styles.css' %}">
Traceback Switch to copy-and-paste view
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner
                response = get_response(request) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/core/handlers/base.py, line 202, in _get_response
                response = response.render() …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/response.py, line 105, in render
            self.content = self.rendered_content …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/response.py, line 83, in rendered_content
        return template.render(context, self._request) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/backends/django.py, line 61, in render
            return self.template.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 170, in render
                    return self._render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 162, in _render
        return self.nodelist.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/loader_tags.py, line 150, in render
            return compiled_parent._render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 162, in _render
        return self.nodelist.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/loader_tags.py, line 62, in render
                result = block.nodelist.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/defaulttags.py, line 312, in render
                return nodelist.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/defaulttags.py, line 211, in render
                    nodelist.append(node.render_annotated(context)) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/defaulttags.py, line 312, in render
                return nodelist.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 938, in render
                bit = node.render_annotated(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/base.py, line 905, in render_annotated
            return self.render(context) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/template/defaulttags.py, line 446, in render
            url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/urls/base.py, line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) …
▶ Local vars
/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/lib/python3.8/site-packages/django/urls/resolvers.py, line 685, in _reverse_with_prefix
        raise NoReverseMatch(msg) …
▶ Local vars
Request information
USER
utente2

GET
No GET data

POST
No POST data

FILES
No FILES data

COOKIES
Variable    Value
csrftoken   
'iD3hPtfJJBZVhspWJCd6lBixHZlQXDGTNNcNxOeXHP8sMPojFWdj44KmuWLhofBt'
sessionid   
'be6093iztc4amp01m5iem5rqs1hpvmfu'
META
Variable    Value
COLORTERM   
'truecolor'
CONTENT_LENGTH  
''
CONTENT_TYPE    
'text/plain'
CSRF_COOKIE 
'iD3hPtfJJBZVhspWJCd6lBixHZlQXDGTNNcNxOeXHP8sMPojFWdj44KmuWLhofBt'
DBUS_SESSION_BUS_ADDRESS    
'unix:path=/run/user/1000/bus,guid=447d4c8bbf6ab158891dbc085fed8d55'
DBUS_STARTER_ADDRESS    
'unix:path=/run/user/1000/bus,guid=447d4c8bbf6ab158891dbc085fed8d55'
DBUS_STARTER_BUS_TYPE   
'session'
DERBY_HOME  
'/usr/lib/jvm/java-15-oracle/db'
DESKTOP_SESSION 
'ubuntu'
DISPLAY 
':0'
DJANGO_SETTINGS_MODULE  
'locallibrary.settings'
GATEWAY_INTERFACE   
'CGI/1.1'
GDMSESSION  
'ubuntu'
GNOME_DESKTOP_SESSION_ID    
'this-is-deprecated'
GNOME_SHELL_SESSION_MODE    
'ubuntu'
GNOME_TERMINAL_SCREEN   
'/org/gnome/Terminal/screen/ad34faf4_0179_4a5f_b2d2_a59f791e49da'
GNOME_TERMINAL_SERVICE  
':1.106'
GPG_AGENT_INFO  
'/run/user/1000/gnupg/S.gpg-agent:0:1'
GTK_MODULES 
'gail:atk-bridge'
HOME    
'/home/andrea'
HTTP_ACCEPT 
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
HTTP_ACCEPT_ENCODING    
'gzip, deflate, br'
HTTP_ACCEPT_LANGUAGE    
'it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7'
HTTP_CONNECTION 
'keep-alive'
HTTP_COOKIE 
('csrftoken=iD3hPtfJJBZVhspWJCd6lBixHZlQXDGTNNcNxOeXHP8sMPojFWdj44KmuWLhofBt; '
 'sessionid=be6093iztc4amp01m5iem5rqs1hpvmfu')
HTTP_HOST   
'localhost:8000'
HTTP_SEC_FETCH_DEST 
'document'
HTTP_SEC_FETCH_MODE 
'navigate'
HTTP_SEC_FETCH_SITE 
'none'
HTTP_SEC_FETCH_USER 
'?1'
HTTP_UPGRADE_INSECURE_REQUESTS  
'1'
HTTP_USER_AGENT 
('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) '
 'Chrome/86.0.4240.183 Safari/537.36')
IM_CONFIG_PHASE 
'1'
INVOCATION_ID   
'717a5ccecd374f5692251368993fbf92'
J2REDIR 
'/usr/lib/jvm/java-15-oracle'
J2SDKDIR    
'/usr/lib/jvm/java-15-oracle'
JAVA_HOME   
'/usr/lib/jvm/java-15-oracle'
JOURNAL_STREAM  
'9:56281'
LANG    
'it_IT.UTF-8'
LANGUAGE    
'it:en'
LC_ADDRESS  
'it_IT.UTF-8'
LC_IDENTIFICATION   
'it_IT.UTF-8'
LC_MEASUREMENT  
'it_IT.UTF-8'
LC_MONETARY 
'it_IT.UTF-8'
LC_NAME 
'it_IT.UTF-8'
LC_NUMERIC  
'it_IT.UTF-8'
LC_PAPER    
'it_IT.UTF-8'
LC_TELEPHONE    
'it_IT.UTF-8'
LC_TIME 
'it_IT.UTF-8'
LESSCLOSE   
'/usr/bin/lesspipe %s %s'
LESSOPEN    
'| /usr/bin/lesspipe %s'
LOGNAME 
'andrea'
LS_COLORS   
'rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.dz=01;31:*.gz=01;31:*.lrz=01;31:*.lz=01;31:*.lzo=01;31:*.xz=01;31:*.zst=01;31:*.tzst=01;31:*.bz2=01;31:*.bz=01;31:*.tbz=01;31:*.tbz2=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.alz=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.cab=01;31:*.wim=01;31:*.swm=01;31:*.dwm=01;31:*.esd=01;31:*.jpg=01;35:*.jpeg=01;35:*.mjpg=01;35:*.mjpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.webm=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=00;36:*.au=00;36:*.flac=00;36:*.m4a=00;36:*.mid=00;36:*.midi=00;36:*.mka=00;36:*.mp3=00;36:*.mpc=00;36:*.ogg=00;36:*.ra=00;36:*.wav=00;36:*.oga=00;36:*.opus=00;36:*.spx=00;36:*.xspf=00;36:'
MANAGERPID  
'1639'
OLDPWD  
'/home/andrea/Documenti/Python-WS/django_projects'
PAPERSIZE   
'a4'
PATH    
'/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/bin:/home/andrea/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/usr/lib/jvm/java-15-oracle/bin:/usr/lib/jvm/java-15-oracle/db/bin'
PATH_INFO   
'/catalog/borrowed/'
PROJECT_HOME    
'/home/andrea/Devel'
PS1 
('(LOCAL-LIBRARY-TUTORIAL-ENV) \\[\\e]0;\\u@\\h: '
 '\\w\\a\\]${debian_chroot:+($debian_chroot)}\\[\\033[01;32m\\]\\u@\\h\\[\\033[00m\\]:\\[\\033[01;34m\\]\\w\\[\\033[00m\\]\\$ ')
PWD 
'/home/andrea/Documenti/Python-WS/django_projects/locallibrary'
QT_ACCESSIBILITY    
'1'
QT_IM_MODULE    
'ibus'
QUERY_STRING    
''
REMOTE_ADDR 
'127.0.0.1'
REMOTE_HOST 
''
REQUEST_METHOD  
'GET'
RUN_MAIN    
'true'
SCRIPT_NAME 
''
SERVER_NAME 
'localhost'
SERVER_PORT 
'8000'
SERVER_PROTOCOL 
'HTTP/1.1'
SERVER_SOFTWARE 
'WSGIServer/0.2'
SESSION_MANAGER 
'local/ubuntu:@/tmp/.ICE-unix/1855,unix/ubuntu:/tmp/.ICE-unix/1855'
SHELL   
'/bin/bash'
SHLVL   
'1'
SSH_AGENT_PID   
'1820'
SSH_AUTH_SOCK   
'/run/user/1000/keyring/ssh'
TERM    
'xterm-256color'
TZ  
'Europe/Rome'
USER    
'andrea'
USERNAME    
'andrea'
VIRTUALENVWRAPPER_HOOK_DIR  
'/home/andrea/.virtualenvs'
VIRTUALENVWRAPPER_PROJECT_FILENAME  
'.project'
VIRTUALENVWRAPPER_PYTHON    
'/usr/bin/python3'
VIRTUALENVWRAPPER_SCRIPT    
'/usr/local/bin/virtualenvwrapper.sh'
VIRTUALENVWRAPPER_VIRTUALENV_ARGS   
' -p /usr/bin/python3 '
VIRTUALENVWRAPPER_WORKON_CD 
'1'
VIRTUAL_ENV 
'/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV'
VTE_VERSION 
'6003'
WINDOWPATH  
'2'
WORKON_HOME 
'/home/andrea/.virtualenvs'
XAUTHORITY  
'/run/user/1000/gdm/Xauthority'
XDG_CONFIG_DIRS 
'/etc/xdg/xdg-ubuntu:/etc/xdg'
XDG_CURRENT_DESKTOP 
'ubuntu:GNOME'
XDG_DATA_DIRS   
'/usr/share/ubuntu:/usr/local/share/:/usr/share/:/var/lib/snapd/desktop'
XDG_MENU_PREFIX 
'gnome-'
XDG_RUNTIME_DIR 
'/run/user/1000'
XDG_SESSION_CLASS   
'user'
XDG_SESSION_DESKTOP 
'ubuntu'
XDG_SESSION_TYPE    
'x11'
XMODIFIERS  
'@im=ibus'
_   
'/home/andrea/Documenti/Python-WS/Environments/LOCAL-LIBRARY-TUTORIAL-ENV/bin/python3'
wsgi.errors 
<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>
wsgi.file_wrapper   
<class 'wsgiref.util.FileWrapper'>
wsgi.input  
<django.core.handlers.wsgi.LimitedStream object at 0x7f0c0434a070>
wsgi.multiprocess   
False
wsgi.multithread    
True
wsgi.run_once   
False
wsgi.url_scheme 
'http'
wsgi.version    
(1, 0)
Settings
Using settings module locallibrary.settings
Setting Value
ABSOLUTE_URL_OVERRIDES  
{}
ADMINS  
[]
ALLOWED_HOSTS   
[]
APPEND_SLASH    
True
AUTHENTICATION_BACKENDS 
['django.contrib.auth.backends.ModelBackend']
AUTH_PASSWORD_VALIDATORS    
'********************'
AUTH_USER_MODEL 
'auth.User'
BASE_DIR    
PosixPath('/home/andrea/Documenti/Python-WS/django_projects/locallibrary')
CACHES  
{'default': {'BACKEND': 'django.core.cache.backends.locmem.LocMemCache'}}
CACHE_MIDDLEWARE_ALIAS  
'default'
CACHE_MIDDLEWARE_KEY_PREFIX 
'********************'
CACHE_MIDDLEWARE_SECONDS    
600
CSRF_COOKIE_AGE 
31449600
CSRF_COOKIE_DOMAIN  
None
CSRF_COOKIE_HTTPONLY    
False
CSRF_COOKIE_NAME    
'csrftoken'
CSRF_COOKIE_PATH    
'/'
CSRF_COOKIE_SAMESITE    
'Lax'
CSRF_COOKIE_SECURE  
False
CSRF_FAILURE_VIEW   
'django.views.csrf.csrf_failure'
CSRF_HEADER_NAME    
'HTTP_X_CSRFTOKEN'
CSRF_TRUSTED_ORIGINS    
[]
CSRF_USE_SESSIONS   
False
DATABASES   
{'default': {'ATOMIC_REQUESTS': False,
             'AUTOCOMMIT': True,
             'CONN_MAX_AGE': 0,
             'ENGINE': 'django.db.backends.sqlite3',
             'HOST': '',
             'NAME': PosixPath('/home/andrea/Documenti/Python-WS/django_projects/locallibrary/db.sqlite3'),
             'OPTIONS': {},
             'PASSWORD': '********************',
             'PORT': '',
             'TEST': {'CHARSET': None,
                      'COLLATION': None,
                      'MIGRATE': True,
                      'MIRROR': None,
                      'NAME': None},
             'TIME_ZONE': None,
             'USER': ''}}
DATABASE_ROUTERS    
[]
DATA_UPLOAD_MAX_MEMORY_SIZE 
2621440
DATA_UPLOAD_MAX_NUMBER_FIELDS   
1000
DATETIME_FORMAT 
'N j, Y, P'
DATETIME_INPUT_FORMATS  
['%Y-%m-%d %H:%M:%S',
 '%Y-%m-%d %H:%M:%S.%f',
 '%Y-%m-%d %H:%M',
 '%m/%d/%Y %H:%M:%S',
 '%m/%d/%Y %H:%M:%S.%f',
 '%m/%d/%Y %H:%M',
 '%m/%d/%y %H:%M:%S',
 '%m/%d/%y %H:%M:%S.%f',
 '%m/%d/%y %H:%M']
DATE_FORMAT 
'N j, Y'
DATE_INPUT_FORMATS  
['%Y-%m-%d',
 '%m/%d/%Y',
 '%m/%d/%y',
 '%b %d %Y',
 '%b %d, %Y',
 '%d %b %Y',
 '%d %b, %Y',
 '%B %d %Y',
 '%B %d, %Y',
 '%d %B %Y',
 '%d %B, %Y']
DEBUG   
True
DEBUG_PROPAGATE_EXCEPTIONS  
False
DECIMAL_SEPARATOR   
'.'
DEFAULT_CHARSET 
'utf-8'
DEFAULT_EXCEPTION_REPORTER  
'django.views.debug.ExceptionReporter'
DEFAULT_EXCEPTION_REPORTER_FILTER   
'django.views.debug.SafeExceptionReporterFilter'
DEFAULT_FILE_STORAGE    
'django.core.files.storage.FileSystemStorage'
DEFAULT_FROM_EMAIL  
'webmaster@localhost'
DEFAULT_HASHING_ALGORITHM   
'sha256'
DEFAULT_INDEX_TABLESPACE    
''
DEFAULT_TABLESPACE  
''
DISALLOWED_USER_AGENTS  
[]
EMAIL_BACKEND   
'django.core.mail.backends.console.EmailBackend'
EMAIL_HOST  
'localhost'
EMAIL_HOST_PASSWORD 
'********************'
EMAIL_HOST_USER 
''
EMAIL_PORT  
25
EMAIL_SSL_CERTFILE  
None
EMAIL_SSL_KEYFILE   
'********************'
EMAIL_SUBJECT_PREFIX    
'[Django] '
EMAIL_TIMEOUT   
None
EMAIL_USE_LOCALTIME 
False
EMAIL_USE_SSL   
False
EMAIL_USE_TLS   
False
FILE_UPLOAD_DIRECTORY_PERMISSIONS   
None
FILE_UPLOAD_HANDLERS    
['django.core.files.uploadhandler.MemoryFileUploadHandler',
 'django.core.files.uploadhandler.TemporaryFileUploadHandler']
FILE_UPLOAD_MAX_MEMORY_SIZE 
2621440
FILE_UPLOAD_PERMISSIONS 
420
FILE_UPLOAD_TEMP_DIR    
None
FIRST_DAY_OF_WEEK   
0
FIXTURE_DIRS    
[]
FORCE_SCRIPT_NAME   
None
FORMAT_MODULE_PATH  
None
FORM_RENDERER   
'django.forms.renderers.DjangoTemplates'
IGNORABLE_404_URLS  
[]
INSTALLED_APPS  
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'catalog.apps.CatalogConfig']
INTERNAL_IPS    
[]
LANGUAGES   
[('af', 'Afrikaans'),
 ('ar', 'Arabic'),
 ('ar-dz', 'Algerian Arabic'),
 ('ast', 'Asturian'),
 ('az', 'Azerbaijani'),
 ('bg', 'Bulgarian'),
 ('be', 'Belarusian'),
 ('bn', 'Bengali'),
 ('br', 'Breton'),
 ('bs', 'Bosnian'),
 ('ca', 'Catalan'),
 ('cs', 'Czech'),
 ('cy', 'Welsh'),
 ('da', 'Danish'),
 ('de', 'German'),
 ('dsb', 'Lower Sorbian'),
 ('el', 'Greek'),
 ('en', 'English'),
 ('en-au', 'Australian English'),
 ('en-gb', 'British English'),
 ('eo', 'Esperanto'),
 ('es', 'Spanish'),
 ('es-ar', 'Argentinian Spanish'),
 ('es-co', 'Colombian Spanish'),
 ('es-mx', 'Mexican Spanish'),
 ('es-ni', 'Nicaraguan Spanish'),
 ('es-ve', 'Venezuelan Spanish'),
 ('et', 'Estonian'),
 ('eu', 'Basque'),
 ('fa', 'Persian'),
 ('fi', 'Finnish'),
 ('fr', 'French'),
 ('fy', 'Frisian'),
 ('ga', 'Irish'),
 ('gd', 'Scottish Gaelic'),
 ('gl', 'Galician'),
 ('he', 'Hebrew'),
 ('hi', 'Hindi'),
 ('hr', 'Croatian'),
 ('hsb', 'Upper Sorbian'),
 ('hu', 'Hungarian'),
 ('hy', 'Armenian'),
 ('ia', 'Interlingua'),
 ('id', 'Indonesian'),
 ('ig', 'Igbo'),
 ('io', 'Ido'),
 ('is', 'Icelandic'),
 ('it', 'Italian'),
 ('ja', 'Japanese'),
 ('ka', 'Georgian'),
 ('kab', 'Kabyle'),
 ('kk', 'Kazakh'),
 ('km', 'Khmer'),
 ('kn', 'Kannada'),
 ('ko', 'Korean'),
 ('ky', 'Kyrgyz'),
 ('lb', 'Luxembourgish'),
 ('lt', 'Lithuanian'),
 ('lv', 'Latvian'),
 ('mk', 'Macedonian'),
 ('ml', 'Malayalam'),
 ('mn', 'Mongolian'),
 ('mr', 'Marathi'),
 ('my', 'Burmese'),
 ('nb', 'Norwegian Bokmål'),
 ('ne', 'Nepali'),
 ('nl', 'Dutch'),
 ('nn', 'Norwegian Nynorsk'),
 ('os', 'Ossetic'),
 ('pa', 'Punjabi'),
 ('pl', 'Polish'),
 ('pt', 'Portuguese'),
 ('pt-br', 'Brazilian Portuguese'),
 ('ro', 'Romanian'),
 ('ru', 'Russian'),
 ('sk', 'Slovak'),
 ('sl', 'Slovenian'),
 ('sq', 'Albanian'),
 ('sr', 'Serbian'),
 ('sr-latn', 'Serbian Latin'),
 ('sv', 'Swedish'),
 ('sw', 'Swahili'),
 ('ta', 'Tamil'),
 ('te', 'Telugu'),
 ('tg', 'Tajik'),
 ('th', 'Thai'),
 ('tk', 'Turkmen'),
 ('tr', 'Turkish'),
 ('tt', 'Tatar'),
 ('udm', 'Udmurt'),
 ('uk', 'Ukrainian'),
 ('ur', 'Urdu'),
 ('uz', 'Uzbek'),
 ('vi', 'Vietnamese'),
 ('zh-hans', 'Simplified Chinese'),
 ('zh-hant', 'Traditional Chinese')]
LANGUAGES_BIDI  
['he', 'ar', 'ar-dz', 'fa', 'ur']
LANGUAGE_CODE   
'en-us'
LANGUAGE_COOKIE_AGE 
None
LANGUAGE_COOKIE_DOMAIN  
None
LANGUAGE_COOKIE_HTTPONLY    
False
LANGUAGE_COOKIE_NAME    
'django_language'
LANGUAGE_COOKIE_PATH    
'/'
LANGUAGE_COOKIE_SAMESITE    
None
LANGUAGE_COOKIE_SECURE  
False
LOCALE_PATHS    
[]
LOGGING 
{}
LOGGING_CONFIG  
'logging.config.dictConfig'
LOGIN_REDIRECT_URL  
'/'
LOGIN_URL   
'/accounts/login/'
LOGOUT_REDIRECT_URL 
None
MANAGERS    
[]
MEDIA_ROOT  
''
MEDIA_URL   
'/'
MESSAGE_STORAGE 
'django.contrib.messages.storage.fallback.FallbackStorage'
MIDDLEWARE  
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']
MIGRATION_MODULES   
{}
MONTH_DAY_FORMAT    
'F j'
NUMBER_GROUPING 
0
PASSWORD_HASHERS    
'********************'
PASSWORD_RESET_TIMEOUT  
'********************'
PASSWORD_RESET_TIMEOUT_DAYS 
'********************'
PREPEND_WWW 
False
ROOT_URLCONF    
'locallibrary.urls'
SECRET_KEY  
'********************'
SECURE_BROWSER_XSS_FILTER   
False
SECURE_CONTENT_TYPE_NOSNIFF 
True
SECURE_HSTS_INCLUDE_SUBDOMAINS  
False
SECURE_HSTS_PRELOAD 
False
SECURE_HSTS_SECONDS 
0
SECURE_PROXY_SSL_HEADER 
None
SECURE_REDIRECT_EXEMPT  
[]
SECURE_REFERRER_POLICY  
'same-origin'
SECURE_SSL_HOST 
None
SECURE_SSL_REDIRECT 
False
SERVER_EMAIL    
'root@localhost'
SESSION_CACHE_ALIAS 
'default'
SESSION_COOKIE_AGE  
1209600
SESSION_COOKIE_DOMAIN   
None
SESSION_COOKIE_HTTPONLY 
True
SESSION_COOKIE_NAME 
'sessionid'
SESSION_COOKIE_PATH 
'/'
SESSION_COOKIE_SAMESITE 
'Lax'
SESSION_COOKIE_SECURE   
False
SESSION_ENGINE  
'django.contrib.sessions.backends.db'
SESSION_EXPIRE_AT_BROWSER_CLOSE 
False
SESSION_FILE_PATH   
None
SESSION_SAVE_EVERY_REQUEST  
False
SESSION_SERIALIZER  
'django.contrib.sessions.serializers.JSONSerializer'
SETTINGS_MODULE 
'locallibrary.settings'
SHORT_DATETIME_FORMAT   
'm/d/Y P'
SHORT_DATE_FORMAT   
'm/d/Y'
SIGNING_BACKEND 
'django.core.signing.TimestampSigner'
SILENCED_SYSTEM_CHECKS  
[]
STATICFILES_DIRS    
[]
STATICFILES_FINDERS 
['django.contrib.staticfiles.finders.FileSystemFinder',
 'django.contrib.staticfiles.finders.AppDirectoriesFinder']
STATICFILES_STORAGE 
'django.contrib.staticfiles.storage.StaticFilesStorage'
STATIC_ROOT 
None
STATIC_URL  
'/static/'
TEMPLATES   
[{'APP_DIRS': True,
  'BACKEND': 'django.template.backends.django.DjangoTemplates',
  'DIRS': ['/home/andrea/Documenti/Python-WS/django_projects/locallibrary/templates'],
  'OPTIONS': {'context_processors': ['django.template.context_processors.debug',
                                     'django.template.context_processors.request',
                                     'django.contrib.auth.context_processors.auth',
                                     'django.contrib.messages.context_processors.messages']}}]
TEST_NON_SERIALIZED_APPS    
[]
TEST_RUNNER 
'django.test.runner.DiscoverRunner'
THOUSAND_SEPARATOR  
','
TIME_FORMAT 
'P'
TIME_INPUT_FORMATS  
['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']
TIME_ZONE   
'Europe/Rome'
USE_I18N    
True
USE_L10N    
True
USE_THOUSAND_SEPARATOR  
False
USE_TZ  
True
USE_X_FORWARDED_HOST    
False
USE_X_FORWARDED_PORT    
False
WSGI_APPLICATION    
'locallibrary.wsgi.application'
X_FRAME_OPTIONS 
'DENY'
YEAR_MONTH_FORMAT   
'F Y'

怎么了?我错过了什么?如何尝试修复我的代码?

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


HttpResponseRedirect错误很可能是在方法views.py的反面renew_book_librarian()

对于传递的参数以reverse('name')传递正确的“名称”,从最初调用函数的位置。


推荐阅读