Error during template rendering? - python

I have a blog app, this is the relevant part of views.py, of course belonging to the blog app.
from django.conf import settings
from django.shortcuts import render
from .models import Blog
# Create your views here.
def view_homepage(request):
return render(request, 'index.html', {})
def view_aboutpage(request):
return render(request, 'about.html', {})
def view_blogpost(request, blog_id):
article = Blog.objects.get(pk=blog_id)
return render(request, 'damn.html', {'article':article})
this is the urls.py in blog app
from django.conf.urls import url, include, patterns
from blog import views
urlpatterns = [
url(r'^$', views.view_homepage, name=''),
url(r'about/$', views.view_aboutpage, name='about'),
url(r'blog/(?P<blog_id>\d+)/$', views.view_blogpost, name='post'),
]
This is the regular urls.py in the project.
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('blog.urls')),
]
This is the error, I am having.
NoReverseMatch at /
Reverse for 'post' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P<blog_id>\\d+)/$']
Request Method: GET
Request URL: http://localhost:8000/
Django Version: 1.9
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'post' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P<blog_id>\\d+)/$']
Exception Location: C:\Users\filip\Python\ENV\lib\site- packages\django\core\urlresolvers.py in _reverse_with_prefix, line 508
Python Executable: C:\Users\filip\Python\ENV\Scripts\python.exe
Python Version: 3.5.1
This is the html:
<li>
Home
</li>
<li>
About
</li>
<li>
Sample Post
</li>
Reverse for 'post' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['blog/(?P\d+)/$']

Like the error says, you don't have a URL called "post" that takes no arguments; the URL you do have called that is expecting a blog_id argument. So, you should pass that in your tag; since you have a context variable called article it would be:
Sample Post

Related

Django, NoReverseMatch. What should I write in this code?

I have a problem:
NoReverseMatch at /update-orders/12
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\\-orders/(?P<pk>[0-9]+)$']
Request Method: GET
Request URL: http://192.168.0.249:8000/update-orders/12
Django Version: 3.0.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\\-orders/(?P<pk>[0-9]+)$']
Exception Location: /root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677
Python Executable: /root/.local/share/virtualenvs/myp4-4l8n6HJk/bin/python
Python Version: 3.7.3
Python Path:
['/var/workspace/myp4/webprint',
'/usr/lib/python37.zip',
'/usr/lib/python3.7',
'/usr/lib/python3.7/lib-dynload',
'/root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages']
Why do I have this Error during template rendering?
detail_order.html
{% extends 'index.html' %}
{% block content %}
<p>Back</p>
<h1>Заказ {{get_order.number_order}}</h1>
<h2>Update</h2>
views.py
class UpdateOrderView(CustomSuccessMessageMixin, UpdateView):
model = Order
template_name = 'detail_order.html'
form_class = OrderForm
success_url = reverse_lazy('detail_order')
success_msg = 'Ok'
def get_context_data(self, **kwargs):
kwargs['update'] = True
return super().get_context_data(**kwargs)
urls.py
from django.contrib import admin
from django.urls import path, include
from .views import *
from print import views
urlpatterns = [
path('', views.home_page, name='index'),
path('orders', views.OrderCreateView.as_view(), name='orders'),
path('update-orders/<int:pk>', views.UpdateOrderView.as_view(), name='update_order'), # THIS PATH
path('delete-orders/<int:pk>', views.DeleteOrderView.as_view(), name='delete_order'),
path('detail-order/<int:pk>', views.DetailOrderView.as_view(), name='detail_order'),
path('login', views.MyprojectLoginView.as_view(), name='login_page'),
path('register', views.RegisterUserView.as_view(), name='register_page'),
path('logout', views.MyprojectLogout.as_view(), name='logout_page'),
]
On your template, please put order.id instead of get_order.id. Then your template code will be :
<h2>Update</h2>

Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name

I am getting the above error when I try to access the landing page.
What am I missing?
Traceback
NoReverseMatch at /
Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name.
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 2.2.6
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'fleet' not found. 'fleet' is not a valid view function or pattern name.
Here is the base.html code
<button>
` Fleet Admin
</button>
and below is the app urls.py file
from django.urls import path
from .admin import fleet_admin_site
app_name = 'trucks'
urlpatterns = [
path('fleet/', fleet_admin_site.urls, name="fleet"),
]
and the main urls.py file
from django.contrib import admin
from django.urls import path, include, reverse
from django.views.generic import TemplateView
urlpatterns = [
path('admin/', include('workers.urls')),
path('admin/', include('trucks.urls')),
path('', TemplateView.as_view(template_name='base.html')),
]
admin.py file where I extend the AdminSite
class FleetAdminSite(admin.AdminSite):
site_header = ''
site_title = ''
index_title = ''
fleet_admin_site = FleetAdminSite(name='fleet_admin')
by seeing your code
you need to add method or class not any extension
path('fleet/', fleet_admin_site.urls, name="fleet"),
path(route, view, kwargs=None, name=None)
refer this
You are including the fleet admin with:
urlpatterns = [
path('fleet/', fleet_admin_site.urls, name="fleet"),
]
You can't do {% url 'trucks:fleet' %} to reverse fleet_admin_site.urls. You need to reverse a particular admin URL.
For example, to reverse the index, you would do:
{% 'trucks:fleet_admin:index' %}
In the above, you use trucks because you have app_name = 'trucks' in the urls.py, fleet_admin because that is the namespace in fleet_admin_site = FleetAdminSite(name='fleet_admin'), and index because that's the view you want to reverse.
Finally, the name in your path() doesn't have any effect, so I would remove it.
urlpatterns = [
path('fleet/', fleet_admin_site.urls),
]

Django NoReverseMatch Error from Template

I have in app_main/templates/app/detail.html:
{% for i in user_items %}
<li>{{ i }}</li>
{% endfor %}
I have in app_main/urls.py:
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'),
And I have in app_main/views.py:
def update_last_clicked(request, username, url):
user = get_object_or_404(User, username=username)
user.item_set.get(url=url).last_clicked += 1
return HttpResponseRedirect(url)
I get the NoReverseMatch Error as follows:
NoReverseMatch at /app_main/u/florin/
Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$']
Request Method: GET
Request URL: http://127.0.0.1:8080/app_main/u/florin/
Django Version: 1.11.3
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$']
Exception Location: /Users/f/Desktop/django/lib/python2.7/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 497
Python Executable: /Users/f/Desktop/django/bin/python
Python Version: 2.7.10
With more:
In template /Users/f/Desktop/django/app/app_main/templates/app_main/detail.html, error at line 5
Reverse for 'update_last_clicked' with keyword arguments '{u'username': u'florin', u'url': u'fg'}' not found. 1 pattern(s) tried: [u'app_main/u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$']
I don't understand what's going on: I just want to update an attribute in the item object that is clicked, but with this code added, it gives me this error when I just go to the detail.html view, whose urlpattern is url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/$', views.detail, name='detail'),
The complete urlpatterns in app_main/urls.py is:
app_name = 'app_main'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/$', views.detail, name='detail'),
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/add_item/$', views.add_item, name='add_item'),
url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'),
]
For reference, app/urls.py has url(r'^app_main/', include('app_main.urls')),
I essentially want to pass the item clicked to a view without a form. I figure since I just need to pass the item's url attribute, I can append it to the current url to pass it. Am I wrong? Do I have to use an AJAX call or a form?
FIX: I kept changing things and what worked was just changing url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>[.]*)/$', views.update_last_clicked, name='update_last_clicked'), to url(r'^u/(?P<username>[a-zA-Z0-9_.-]+)/update_last_clicked/(?P<url>.*)/$', views.update_last_clicked, name='update_last_clicked'),. Does anyone understand why simply taking out the grouping brackets changes this?
You have to give a namespace to the app.
For eg -
url(r'^app_main/', include('app_main.urls', namespace='app_main'))
Similary, for all other apps for which you are going to reverse based on app and url name.
You can also do this by mentioning the app_name in app_main/urls.py like this -
app_name = 'app_main'
urlpatterns = [...]
Ref: https://docs.djangoproject.com/en/1.11/topics/http/urls/#reversing-namespaced-urls

NoReverseMatch at display/success/

In the get_success_URL method of FileView , i used 'display:redirect' as the URL to be redirected . But i am getting an error as
Reverse for 'redirect' with arguments '()' and keyword arguments '{'pk': 15}' not found. 1 pattern(s) tried: ['display/success/']
Request Method: POST
Request URL: http://127.0.0.1:8000/display/upload/
Django Version: 1.10.dev20160512164014
Exception Type: NoReverseMatch
Exception Value:
Am I missing something?
display/views.py
class FileView(FormView):
template_name = 'display/upload.html'
form_class = FileForm
def form_valid(self, form):
file_upload = FileModel(file=self.get_form_kwargs().get('files')['file'])
file_upload.save()
self.id = file_upload.id
return HttpResponseRedirect(self.get_success_url())
def get_success_url(self):
return reverse('display:redirect', kwargs={'pk': self.id})
def redirect(request):
return render(request,"display/success.html")
display/urls.py
from django.conf.urls import url
from django.conf.urls.static import static
from django.conf import settings
from . import views
from display.views import FileView
urlpatterns = [
url(r'^start/', views.initial,name='home'),
url(r'^upload/',FileView.as_view(),name='upload'),
url(r'^success/',views.redirect,name='redirect'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Look at this line:
Reverse for 'redirect' with arguments '()' and keyword arguments '{'pk': 15}' not found.
The error message is telling you what's wrong. You've passed a keyword argument and when it tries to reverse / find the url it doesn't because you have the url specified as:
url(r'^success/',views.redirect,name='redirect')
Which doesn't accept any arguments. One possibility is to make your url into this:
^success/(?P<pk>\d+)/$

Django NoReverseMatch exception with cache_page in urls.py

Question
Why does using the cache_page function in urls.py under Django 1.4 cause a NoReverseMatch error when using the url tag in a template?
Setup
views.py
from django.shortcuts import render
def index(request):
'''Display the home page'''
return render(request, 'index.html')
urls.py
Following the cache_page directions:
from django.conf.urls import patterns, include, url
from django.views.decorators.cache import cache_page
from my_project.my_app import views
urlpatterns = patterns('',
url(r'^$', cache_page(60 * 60)(views.index)),
)
index.html
{% url my_project.my_app.views.index %}
Error Message
NoReverseMatch at /
Reverse for 'my_project.my_app.views.index' with arguments '()' and keyword arguments '{}' not found.
The offending line the error message points out is, of course:
{% url my_project.my_app.views.index %}
What I've tried so far
A ton of googling and searching on SO
Simplifying code down to the example above to rule out other conflicts
Used cache_page in views.py as a decorator successfully (not recommended according to docs)
Offerings to our all-powerful Django overlords
When doing reverse, Django tries to match by
URL label
dotted path
callable
In your code, 'my_project.my_app.views.index' is dotted path, then Django would get the actual function index() and use it as the key to match the reversed URL, by looking up in the mapping dictionary django.core.urlresolvers.get_resolver(None).reverse_dict.
However, when you wrap the view.index by cache_view, the key in the mapping dictionay becomes the wrapper. Thus the lookup fails and NoReverseMatch is raised. This is inconvenient and error-prone, but I'm not sure whether it is a bug.
You could then solve this by either use URL label
url(r'^$', cache_page(60 * 60)(views.index), name='my_index'),
{# in template #}
{% url my_index %}
or used cache_page in views.py as a decorator as you mentioned.

Categories