Having trouble figuring out why I keep getting the NoReverseMatch.
app/url.py
from django.conf.urls import url, patterns
from . import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<contact_id>\d+)/detail/$', views.details, name='details'),
)
views.py
from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.views import generic
from django.template import RequestContext, loader
from .models import Person
# Create your views here.
class IndexView(generic.ListView):
template_name = 'ContactManager/index.html'
context_object_name = 'contact_list'
def get_queryset(self):
return Person.objects.order_by('lname')
def details(request, contact_id):
contact = get_object_or_404(Person, id=contact_id)
return render(request, 'ContactManager/details.html', {'contact': contact})
# class DetailView(generic.ListView):
# model = Person
# context_object_name = 'contact'
# template_name = 'ContactManager/details.html'
#
# def get_queryset(self):
#
template index.html
{% if contact_list %}
<ul>
{% for contact in contact_list %}
<li>
{{ contact.fname }} {{ contact.lname }}
</li>
{% endfor %}
</ul>
{% else %}
<p>You don't have any contacts currently.</p>
{% endif %}
The error I am getting:
Reverse for 'details' with arguments '()' and keyword arguments '{'contact_id': 1}' not found. 1 pattern(s) tried: ['$(?P<contact_id>\\d+)/detail/$']
I have tried using generic views and a host of arguments in the {% url ... %}
Any help would be much appreciated.
I think that details url pattern has a mistake, in error message appears one tried pattern, started and ended by $ sign:
1 pattern(s) tried: ['$(?P\d+)/detail/$']
check your pattern that is equal to or no:
^(?P<contact_id>\\d+)/detail/$
if this is correct check your urls file that included contact urls and if is similar below:
url('^$', include(ContactManager.urls, namespace='contact'))
remove $ sign at end of prefix-pattern:
url('^', include(ContactManager.urls, namespace='contact'))
Note that this error can also arise if you do not define name in your urlpatterns.
Doing something like
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^error_containing_view/$', views.error_containing_view, name='error_containing_view'),
]
in your app's urls.py would fix the error.
Related
I have an app that is going to display some information about people in my group. I'm getting a NoReverseMatch error when trying to use the url tag in my index.html. If I do not use the url tag, but specify the root, I do not receive the error.
The error says:
NoReverseMatch at /
Reverse for 'specialist' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['$(?P[0-9]+)/']
Here is are the urls.py files.
From the main wi_tech urls.py:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^$', include('person.urls')),
url(r'^tech/', include('person.urls')),
url(r'^admin/', admin.site.urls),
]
From the 'person' app urls.py:
from django.conf.urls import url
from . import views
app_name = 'person'
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist'),
]
My views.py file looks like this:
from django.views import generic
from .models import Specialist
class IndexView(generic.ListView):
template_name = 'person/index.html'
context_object_name = 'person_list'
def get_queryset(self):
"""Return all specialists"""
return Specialist.objects.order_by('id')
class DetailView(generic.DetailView):
model = Specialist
template_name = 'person/detail.html'
And my index.html page looks like this:
{% if person_list %}
<ul>
{% for specialist in person_list %}
<li> {{ specialist }}</li>
{% endfor %}
</ul>
{% else %}
<p>No specialists are available.</p>
{% endif %}
If I change my tag in index.html to this, it works:
<li> {{ specialist }}</li>
Obviously this isn't an ideal situation in case the web root ever changes. I've reviewed a lot of SO questions on this, and nothing seems to match. I think the issue is the "$" in the beginning of the regex, but I don't see where that's coming from.
Specifically, I used this link as a really good reference point, but came up empty looking through my code.
what is NoReverseMatch and how do i fix it
Clearly there's something I'm missing.
Could it be the additional / at the end of the URL?
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist')
The one after your primary key modifier. When you click the URL (with the (% url ':' model.name %)) what URL comes up in your browser?
I ended up scrapping this implementation, and going with a flatter structure whereby all models, views and templates are in the same application. I have not had this problem in the new design.
I am trying to pass configure a URL like so:
/details/12345
Template HTML:
<div class="row">
{% if article_list %}
{% for article in article_list %}
<div>
<h2>{{ article.title }}</h2>
<p>{{ article.body }}</p>
<p><a class="btn btn-default" href="{% url 'details' article.id %}" role="button">View details ยป</a></p>
</div><!--/.col-xs-6.col-lg-4-->
{% endfor %}
{% endif %}
</div><!--/row-->
urls.py (full):
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'news_readr.views.home', name='home'),
url(r'^details/(?P<article_id>\d+)/$', 'news_readr.views.details', name='details'),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py:
from django.shortcuts import render
from .models import Article
# Create your views here.
def home(request):
title = "Home"
article_list = Article.objects.all()
for article in article_list:
print(article.id)
context = {
"title": title,
"article_list": article_list,
}
return render(request, "home.html", context)
def details(request, article_id = "1"):
article = Article.objects.get(id=article_id)
return render(request, "details.html", {'article': article})
I am getting an error that says:
NoReverseMatch at /
Reverse for 'details' with arguments '()' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['details/(?P<article_id>\\d+)/$']
I'm one week old at Django, and I think there's something wrong with my URL Named Group config. Please help! TIA!
Update: If I remove the URL config and change it back to:
url(r'^details/$', 'news_readr.views.details', name='details'),
The error changes to:
Reverse for 'details' with arguments '(1,)' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['details/$']
So it seems to be picking up the argument that is passed 1 in this case. So this seems to be an issue with the regular expression. I tried the expression out at Pythex, but even there, the expression doesn't seem to be matching anything.
For the url pattern
url(r'^details/(?P<article_id>\d+)/$', 'news_readr.views.details', name='details'),
The correct way to use the tag is
{% url 'details' article.id %}
This because the details url pattern has a group article_id, so you have to pass this to the tag.
If you have the above url pattern, and {{ article.id}} displays correctly in the template, then the above template tag should not give the error Reverse for 'details' with arguments '()'. That suggests you have not updated the code, or you have not restarted the server after changing code.
If you change the url pattern to
url(r'^details/$', 'news_readr.views.details', name='details')
then you need to remove the article.id from the url tag.
{% url 'details' %}
I guess your pattern is wrong.( not an expert of regex ).
Try this
url(r'^details/((?P<article_id>[0-9]+)/$', 'news_readr.views.details', name='details'),
I am getting the following error:
NoReverseMatch at /lld/new/
Reverse for 'display_lld' with arguments '()' and
keyword arguments '{'slug': u'stack-overflow-new-document'}' not found.
0 pattern(s) tried: []
I can't get to the bottom of it, though I think it has something to do with either my url regex or the document.slug variable passed to the index.html template in views.py.
views.py:
from django.shortcuts import get_object_or_404, render, redirect
from .models import Document
from .forms import DocumentForm
def index(request):
document_list = Document.objects.order_by('-date_updated')
context = {'document_list': document_list}
return render(request, 'lld/index.html', context)
def display_lld(request, slug):
document = get_object_or_404(Document, slug=slug)
return render(request, 'lld/display_lld.html', {'document': document})
def new_lld(request):
if request.method == "POST":
form = DocumentForm(request.POST)
if form.is_valid():
document = form.save(commit=False)
document.save()
return redirect('display_lld', slug=document.slug)
else:
form = DocumentForm()
return render(request, 'lld/new_lld.html', {'form': form})
site urls.py:
urlpatterns = [
url(r'^lld/', include('lld.urls', namespace="lld")),
url(r'^admin/', include(admin.site.urls)),
]
app urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# example: /lld/
url(r'^$', views.index, name='index'),
# example: /lld/new/
url(r'^new/$', views.new_lld, name='new_lld'),
# ex: /lld/customername-projectname/
url(r'^(?P<slug>([\w-]+))/', views.display_lld, name='display_lld'),
]
index.html:
{% if document_list %}
<ul>
{% for document in document_list %}
<li>{{ document.customer }} / {{ document.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No documents are available.</p>
{% endif %}
Create New LLD
The form creates the new document fine, it shows up in the admin. But when I click on the forms save button it brings up the NoReverseMatch error rather than redirecting back to the created document. The newly created document is listed on the index page and I can navigate to it by clicking on it's link there, it just appears to throw the error in the form redirect.
When calling redirect, you have left out the lld namespace. You need to include the namespace when you use redirect or reverse, the same way as you already do when you use the {% url %} tag in your templates:
return redirect('lld:display_lld', slug=document.slug)
from django.core.urlresolvers import reverse
return redirect(reverse('lld:display_lld', args=[document.slug]))
The error points to the {% url product %}
NoReverseMatch at /category/
Reverse for '' with arguments '()' and keyword arguments '{}' not found.
Request Method: GET
Request URL: http://127.0.0.1:8000/category/
Django Version: 1.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for '' with arguments '()' and keyword arguments '{}' not found.
Exception Location: C:\Python27\lib\site-packages\django\template\defaulttags.py in render, line 424
Python Executable: C:\Python27\python.exe
Python Version: 2.7.2
My HTML
<html>
<body>
<p> The list of items are </p>
{% for items in allobs %}
<li>{{items}}</li>
{% endfor %}
<p>Product list</p>
</body>
</html>
My VIEWS
from django.http import HttpResponse, Http404
from models import Category, Product
from datetime import datetime, timedelta, date, time
from django.shortcuts import render_to_response
def hello(request):
return HttpResponse("Hello World")
def category(request):
cat = Category.objects.all()
return render_to_response('category.html',{'allobs': cat})
def product(request):
pro = Product.objects.all()
return render_to_response('product.html',{'allobs':pro})
MY URLS
from django.conf.urls.defaults import *
from django.contrib import admin
from website.views import hello, category, product
from django.conf import settings
admin.autodiscover()
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^hello/$', hello),
url(r'^category/$', category),
(r'^tinymce/', include('tinymce.urls')),
url(r'^product/$', product),
)
if settings.DEBUG:
urlpatterns += patterns('django.views.static',
(r'images/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}),
)
Guess {% url product %} should be {% url 'product' %} if product is the name of your view.
Edit: Also use the full name of the view 'product.views.product'.
I'm doing the Django tutorial, part 3: https://docs.djangoproject.com/en/dev/intro/tutorial03/
I currently have this text in my views.py:
from django.http import HttpResponse
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
output = ', '.join([p.question for p in latest_poll_list])
return HttpResponse(output)
This works when i go to:
http://localhost:8000/polls/, it displays the records
The problem is when I take the next step and change the views.py to:
from django.shortcuts import render
from polls.models import Poll
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
From http://localhost:8000/polls/ it shows the following error:
TemplateDoesNotExist at /polls/
From http://localhost:8000/polls/index.html it shows this error:
Page not found (404)
I have my mysite/urls.py set to:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
I have my poll/views.py set to:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
I have my TEMPLATE_DIRS set to:
'/path/to/mysite/templates'
Why won't the page load with the new code?
You don't show the entire TEMPLATE_DIRS setting. But I suspect you have this:
TEMPLATE_DIRS = (
'/path/to/mysite/templates'
)
when you should actually have this:
TEMPLATE_DIRS = (
'/path/to/mysite/templates',
)
Note the extra comma after the end of the string. The comma is required for a single-element tuple in Python - otherwise, it's just a string in brackets.
Create a folder named polls in templates directory and create an index.html file in it with the following content.
<html>
<body>
<ul>
{% for p in latest_poll_list %}
<li>{{ p.question }}</li>
{% endfor %}
</ul>
</body>
</html>