I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django
I was following the django documentation and making a simple poll app. I have come across the following error :
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^polls/
^admin/
The current URL, , didn't match any of these."
settings.py
ROOT_URLCONF = 'mysite.urls'
mysite/mysite/urls.py
from django.conf.urls import include,url
from django.contrib import admin
urlpatterns = [
url(r'^polls/',include('polls.urls')),
url(r'^admin/', admin.site.urls),]
mysite/polls/urls.py
from django.conf.urls import url
from . import views
app_name= 'polls'
urlpatterns=[
url(r'^$',views.IndexView.as_view(),name='index'),
url(r'^(?P<pk>[0-9]+)/$',views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>[0-9]+)/results/$',views.ResultsView.as_view(),name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$',views.vote,name='vote'),]
mysite/polls/views.py
from django.shortcuts import get_object_or_404,render
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.views import generic
from django.utils import timezone
from django.template import loader
from .models import Choice,Question
from django.template.loader import get_template
#def index(request):
# return HttpResponse("Hello, world. You're at the polls index")
class IndexView(generic.ListView):
template_name='polls/index.html'
context_object_name='latest_question_list'
def get_queryset(self):
"""Return the last five published questions."""
return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[5:]
class DetailView(generic.DetailView):
model=Question
template_name='polls/detail.html'
def get_queryset(self):
"""
Excludes any questions that aren't published yet.
"""
return Question.objects.filter(pub_date__lte=timezone.now())
class ResultsView(generic.DetailView):
model= Question
template_name ='polls/results.html'
def vote(request, question_id):
question=get_object_or_404(Question, pk=question_id)
try:
selected_choice= question.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/details.html',
{
'question':question,
'error_message' : "You didn't select a choice" ,
})
else:
selected_choice.votes+=1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
index.html
<!DOCTYPE HTML >
{% load staticfiles %}
<html>
<body>
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}" />
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li><a href="{% url 'polls:detail' question.id %}">{{question.question_test }}
</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
</body>
</html>
This link http://127.0.0.1:8000/polls/ shows a blank page with 3 bullets. (I have 3 questions in my database and their id's are 5,6,7 because I have been deleting and adding the questions.)
My admin works fine!
I'm new to Django and have been searching and asking around and have been stuck on it for a while now.
You get the 404 on http://127.0.0.1:8000/ because you have not created any URL patterns for that url. You have included the url http://127.0.0.1:8000/polls/, because you have included the polls urls with
url(r'^polls/',include('polls.urls')),
The empty bullets suggest that there is a problem with your polls/index.html template. It looks like you have a typo and have put {{ question.question_test }} instead of {{ question.question_text }}. Make sure that it exactly matches the template from the tutorial 3:
{% if latest_question_list %}
<ul>
{% for question in latest_question_list %}
<li>{{ question.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Make sure there is no typo in your code. Putting space between inverted commas can also lead to this error. Just make sure you have put path('',include('home.urls')) and not path(' ',include('home.urls'))
Note: here home.urls is the name of my app in Django
Am following along on the django tutorial (1.6 python 3.3). Am however stuck in trying to replicate the tutorial in my own test application.
I want to display a list of just 3 hyperlinks on the index page. The hyperlink for now is just the name of listed item.
Views.py
def Index(request):
tables = []
tables.append('Country')
tables.append('County')
tables.append('Registration Body')
return render(request, 'test_app/index.html', {'table_list': tables})
Urls.py
from django.conf.urls import patterns, url
from test_app import views
urlpatterns = patterns('test_app',
#url(r'^Country/', views.Index, name='index'),
url(r'^$', views.Index, name='index'),
)
Index.html
<h1>List of Config Tables in TestApp</h1>
{% if table_list %}
<ul>
{% for tbl_name in table_list %}
<li>{{ tbl_name }}</li>
{% endfor %}
</ul>
{% else %}
<ul>
<p>No table found<p>
</ul>
{% endif %}
With that setup, I get the error:
NoReverseMatch at /test_app/
Reverse for 'index' with arguments '('Country',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['test_app/$']
Something weird is that when I get rid of the tbl_name in href in the index page I am able to get my list but the list DOESN'T have hyperlinks.
I'm working on simple a pet store app
I encountered this error a couple of times and I managed to understand it and fix it but in this situation . I don't know what went wrong . Everything seem clear to me .
It says I have an error in my store.html at the location of the {% url world:brazil animal.id %} but I have define the namespace already.
Reverse for 'brazil' with arguments '('',)' and keyword arguments '{}' not found.
Error during template rendering
In template C:\djcode\mysite\pet\templates\store.html, error at line 5
Reverse for 'brazil' with arguments '('',)' and keyword arguments '{}' not found.
1 Sydney's Pet Store
2 {% if store %}
3 <ul>
4 {% for a in store %}
5 <li><a href ="{% url world:brazil animal.id %}">{{ a.name }}</li>
6 {% endfor %}
7
8 </ul>
9 {% endif %}
My store.html
Sydney's Pet Store
{% if store %}
<ul>
{% for a in store %}
<li><a href ="{% url world:brazil animal.id %}">{{ a.name }}</li>
{% endfor %}
</ul>
{% endif %}
My views.py
from pet.models import Store , Pet
from django.shortcuts import render_to_response ,get_object_or_404
def index(request):
store = Store.objects.all()
return render_to_response ('store.html',{'store':store})
def brazil(request , animal_id):
store = get_object_or_404(Store , Pet, pk=animal_id)
return render_to_response ('animal.html',{'store':store})
My pet app URLCONF:
from django.conf.urls import patterns,include , url
urlpatterns = patterns ('pet.views',
url(r'^$','index',name = 'index'),
url(r'^(?P<poll_id>\d+)/$','brazil',name ='brazil'),
)
my main URCONF:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = patterns('',
url(r'^pet/',include('pet.urls' , namespace='world' )),
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += staticfiles_urlpatterns()
Because you didn't define animal.id. What you have render in your view is only store variable.
Sydney's Pet Store
{% if store %}
<ul>
{% for a in store %}
<li><a href ="{% url world:brazil a.id %}">{{ a.name }}</li>
{% endfor %}
</ul>
{% endif %}
Yesterday I was working on my first app using this tutorial. It's a Poll and Choice app.
The first page displays the question and when you click on the question it's suppose to display choices which you can vote on them.
I had great people who helped me yesterday and told me to use namespace. I've read the namespace tutorial and tried to apply my knowledge
to the scenario but it isn't working so far.
This is my error when I click on the questions which is the first page.
NoReverseMatch at /polls/5/
u"'polls" is not a registered namespace
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/5/
Django Version: 1.4.3
Exception Type: NoReverseMatch
Exception Value:
u"'polls" is not a registered namespace
Exception Location: C:\hp\bin\Python\Lib\site-packages\django\template\defaulttags.py in render, line 424
Python Executable: C:\hp\bin\Python\python.exe
Python Version: 2.5.2
Python Path:
['C:\\djcode\\mysite',
'C:\\hp\\bin\\Python\\python25.zip',
'C:\\hp\\bin\\Python\\DLLs',
'C:\\hp\\bin\\Python\\lib',
'C:\\hp\\bin\\Python\\lib\\plat-win',
'C:\\hp\\bin\\Python\\lib\\lib-tk',
'C:\\hp\\bin\\Python',
'C:\\hp\\bin\\Python\\lib\\site-packages',
'C:\\hp\\bin\\Python\\lib\\site-packages\\win32',
'C:\\hp\\bin\\Python\\lib\\site-packages\\win32\\lib',
'C:\\hp\\bin\\Python\\lib\\site-packages\\Pythonwin']
Server time: Fri, 15 Feb 2013 21:04:10 +1100
Error during template rendering
In template C:\djcode\mysite\myapp\templates\myapp\detail.html, error at line 5
u"'polls" is not a registered namespace
1 <h1>{{ poll.question }}</h1>
2
3 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
4
5 {% url 'polls:vote' poll.id %}
6 {% csrf_token %}
7 {% for choice in poll.choice_set.all %}
8 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
9 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
10 {% endfor %}
11 <input type="submit" value="Vote" />
12 </form>
Now I know the problems are hidden in detail.html, my main urls and my app called myapp URLCONF and views.py
Now My main URLconf are:
C:\djcode\mysite\mysite
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
#url(r'^polls/', include('myapp.urls')),
url(r'^polls/', include('myapp.urls', namespace='polls')),
url(r'^admin/', include(admin.site.urls)),
)
My app folder is called myapp and this is myapp URLconf:
C:\djcode\mysite\myapp
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls import patterns, include, url
urlpatterns = patterns('myapp.views',
url(r'^$', 'index'),
url(r'^(?P<poll_id>\d+)/$', 'detail'),
url(r'^(?P<poll_id>\d+)/results/$', 'results'),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
)
My views.py inside myapp are:
from django.http import HttpResponse
from myapp.models import Poll ,choice
from django.template import Context, loader
from django.http import Http404
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('myapp/index.html', {'latest_poll_list': latest_poll_list})
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/results.html', {'poll': p})
def vote(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
# Redisplay the poll voting form.
return render_to_response('myapp/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
selected_choice.votes += 1
selected_choice.save()
# Always return an HttpResponseRedirect after successfully dealing
# with POST data. This prevents data from being posted twice if a
# user hits the Back button.
return HttpResponseRedirect(reverse('myapp.views.results', args=(p.id,)))
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('myapp/detail.html', {'poll': p},
context_instance=RequestContext(request))
My detail.html
C:\djcode\mysite\myapp\templates\myapp
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
{% url 'polls:vote' poll.id %}
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
The answer is to add namespaces to your root URLconf. In the mysite/urls.py file (the project’s urls.py, not the application’s), go ahead and change it to include namespacing:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
url(r'^admin/', include(admin.site.urls)),
)
Furthermore, in part 3 of the tutorial Namespacing URL names the use of app_name is mentioned as the accepted way for adding the polls namespace. You can add the line for this in your polls/urls.py as follows:
app_name = 'polls'
urlpatterns = [
...
]
Following the same Django tutorial and having the same names,
I had to change in mysite/urls.py
from:
url(r'^polls/', include('polls.urls')),
to:
url(r'^polls/', include('polls.urls', namespace="polls")),
Django 2.0
in yourapp/urls.py
from django.urls import path
from . import views
app_name = 'yourapp'
urlpatterns = [
path('homepage/', views.HomepageView.as_view(), name='homepage'),
]
in urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('yourapp/', include('yourapp.urls')),
]
You need to add the following line to the top of the detail.html:
{% load url from future %}
(Notice you've already used this line in the index.html in order to use the polls namespace)
Inside myapp/urls.py add the following module-level attribute:
app_name = "polls"
This will set the "application namespace name" for that application. When you use names like "polls:submit" in a reverse, Django will look in two places: application namespaces (set like above), and instance namespaces (set using the namespace= parameter in the "url" function). The latter is important if you have multiple instances of an app for your project, but generally it's the former you want.
I had this very issue, and setting namespace= into the url() function seemed wrong somehow.
See this entry of the tutorial: https://docs.djangoproject.com/en/1.9/intro/tutorial03/#namespacing-url-names
Update: this information is correct for Django 1.9. Prior to 1.9, adding a namespace= attribute to the include is, indeed, the proper way.
I think you missed the namespace:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls', namespace="polls")),
)
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.conf import settings
urlpatterns = patterns('myapp.views',
url(r'^$', 'index', name="index"),
url(r'^(?P<poll_id>\d+)/$', 'detail', name="detail"),
url(r'^(?P<poll_id>\d+)/results/$', 'results', name="results"),
url(r'^(?P<poll_id>\d+)/vote/$', 'vote', name="vote"),
)
----------------------------------
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form method="post" action="{% url myapp:vote poll.id %}">
{% csrf_token %}
{% for choice in poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Replacing the line:
{% url 'polls:vote' poll.id %}
with:
{% url 'vote' poll.id %}
worked out for me...
I also faced the same issue.
it is fixed now by adding
app_name = "<name of your app>" in app/urls.py
namespace should be added polls/urls.py file.
url(r'^myapp/$', include('myapp.urls', namespace ='myapp')),
For anyone using "django-hosts":
I had the same error and for me adding this to my template solved it (without any us of namespace etc.):
{% load hosts %}
Admin dashboard
Additionaly I added PARENT_HOST = 'YOUR_PARENT_HOST' to my settings.py
Reference
The problem is in the tutorial.
While adding the namespace( in your case 'myapp') to your URLconf, the tutorial uses the following code of line:
app_name = 'myapp'
The Django framework for some reason treats it as a unicode string. Instead please enclose the name of your app in double quotes instead of single quotes.
For example,
app_name = "myapp"
This will most certainly solve your problem. I had the same problem and doing so solved it.
Restart the web server. Just that.