简体   繁体   中英

Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P<pk>[0-9]+)$']

My website is working well on my local environment, as well as it has been working well on heroku env until my recent deployment. Code is same on both environments and I referred to all 11 posts related to similar issue,example Reverse for 'todo-user' with arguments '('',)' not found. 1 pattern(s) tried

My issue looks different than what I have seen in other posts here, I think it is related to environment settings/variables, which I am not able to identify it yet. But the solutions provided on stack overflow, makes me think like the real problem of this issue is something else.

When I try to click on http://127.0.0.1:8000/catalog/mybooks/ link, local website works fine, however, production (heroku), same code throws following exception


NoReverseMatch at /catalog/mybooks/
Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P<pk>[0-9]+)$']
Request Method: GET
Request URL:    https://<myapp>.herokuapp.com/catalog/mybooks/
Django Version: 2.2.5
Exception Type: NoReverseMatch
Exception Value:    
 Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P<pk>[0-9]+)$']
 Exception Location:    /app/.heroku/python/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 673
 Python Executable: /app/.heroku/python/bin/python
 Python Version:    3.7.3
 Python Path:   
['/app/.heroku/python/bin',
 '/app',
 '/app/.heroku/python/lib/python37.zip',
 '/app/.heroku/python/lib/python3.7',
 '/app/.heroku/python/lib/python3.7/lib-dynload',
 '/app/.heroku/python/lib/python3.7/site-packages']
 Server time:   Wed, 9 Oct 2019 04:52:47 +0000
 Error during template rendering
 In template /app/catalog/templates/base_generic.html, error at line 7
 Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['catalog/book/(?P<pk>[0-9]+)$']

This looks like a misleading error to me.

Also, because the code is working as expected on my local (ie, showing me all the data), so it doesn't look like a coding issue and so I am not able to understand real problem here (and provided solutions for other similar issues)


I have applied all migrations, so environment looks okay:

$ heroku run python manage.py migrate --remote heroku-prod
 Running python manage.py migrate on <my app>... starting, run.5216 (Free)
 Running python manage.py migrate on <my app>... connecting, run.5216 (Free)
 Running python manage.py migrate on <my app>... up, run.5216 (Free)
 Operations to perform:
  Apply all migrations: admin, auth, catalog, contenttypes, sessions, social_django
 Running migrations:
  No migrations to apply.

HP@HP-PC MINGW64 ~/git_projects/prod/django_local_library (master)

Code on DEV/staging, that is also same.

Code: urls.py for links related to book

urlpatterns = [
    path('books/', views.BookListView.as_view(), name='books'),
    path('book/<int:pk>', views.BookDetailView.as_view(), name='book-detail'),
    path('mybooks/', views.LoanedBooksByUserListView.as_view(), name='my-borrowed'),
]

views.py

class BookDetailView(LoginRequiredMixin, generic.DetailView):
    model = Book

    def get_context_data(self, **kwargs):
        context = super(BookDetailView, self).get_context_data(**kwargs)
        process_data(self.request)
        return context

class LoanedBooksByUserListView(LoginRequiredMixin, generic.ListView):
    """Generic class-based view listing books on loan to current user. """
    model = BookInstance
    template_name = 'catalog/bookinstance_list_borrowed_user.html'

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

    def get_context_data(self, **kwargs):
        context = super(LoanedBooksByUserListView, self).get_context_data(**kwargs)
        process_data(self.request)
        return context

Template

{% 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 }})
      </li>
      {% endfor %}

Yesterday night, after this post, I turned off DEBUG for security purpose, ie set DEBUG=False for staging env, as well as for local and added host on ALLOWED_HOSTS, local and staging work fine, however prod is throwing 500 error:

FYI: staging and prod have same configurations, except host name

Ref Setting DEBUG = False causes 500 Error

If I rollback to previous committed code, it starts throwing error highighted in this ques

And if I verify directly on heroku

HP@HP-PC MINGW64 ~/git_projects/prod/django_local_library (master) $ heroku run python manage.py runserver --remote heroku-prod

It doesn't throw any exception:

Performing system checks...
System check identified no issues (0 silenced).
October 09, 2019 - 21:18:54
Django version 2.2.5, using settings 'locallibrary.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

Even the staging logs have no error.

Please help me if someone has ever faced any such issue.

Solution to my problem was fixed when I followed What is a NoReverseMatch error, and how do I fix it? and NoReverseMatch django - not a valid view function or pattern

And I think all such/similar issues should point to the above link.

Root cause: Data was corrupted, I deleted corrupted data, and the issue was fixed without any change in the code.

Steps: I faced similar issue for another new page that I added recently, but the root cause was different (it was due to url formed was incorrect), and the above link helped me identifying the real cause of this issue. I carefully looked into details, including url formed and the page from where url was being referred and finally the data. And the website currently looks like this https://www.realityseekers.com/

Same problem to me. All the things were fine except the contents in the table bookinstances. Somehow, there were several rows in bookinstances misleading, and that rows had not the correspondet row at the table books... There were bookinstances without books, and when the view tries to get the data, the for bucle got nothing, and when the code: {% url 'book-detail' bookinst.book.pk %}" tries to do the reverse of nothing, all the things go wrong... But the dissapointing thing here, is that this kind of error should be best interpreted by Django.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM