NoReverseMatch Django Tutorial 1.8 chapter 4 - python

So I'm also getting the noReverseMatch error at the very end of the 4th chapter of the Django tutorial. But none of the other answers seems to help out in my case. And I can't understand why the tutorial would provide something that doesn't work.
I type everything myself, so there could certainly be a typo somewhere, but I've tried exchanging all the code with copy/paste from chapter 4, and I'm still getting the same error:
Here is the error:
NoReverseMatch at /polls/
Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$']
Error during template rendering
In template /home/MyName/tutorial/mysite/polls/templates/polls/index.html, error at line 4
Reverse for 'detail' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<pk>[0-9]+)/$']
Here is urls.py:
from django.conf.urls import url
from . import views
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')
]
Here is views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.views import generic
from .models import Question, Choice
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Question.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
def vote(request, question_id):
p = get_object_or_404(Question, pk=question_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render(request, 'polls/detail.html', {
'question':p,
'error_message': "You didn't select a choice",})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(p.id,)))
And here is index.html:
{% 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 %}

Change this
{% url 'polls:detail' question_id %} to {% url 'polls:detail' question.id %}

You are rendering question so to access its value it should be question.value not question_value:
user {% url 'polls:detail' question.id %"
where question.id is the numeric argument to the url.

Related

My django didnt work(I'm studying in tutorial)

I'm very new to django. So I'm studying using tutorial site.
I think type perfectly same on site, but it's not work.
so plz give me advice.
mysite/urls.py
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
mysite/polls/urls.py
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'), #url : base/polls/
path('<int:question_id>/', views.detail, name='detail'),
path('<int:question_id>/results/', views.results, name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
]
mysite/polls/templates/polls/detail.html
<h1>{{ question.question_text }}</h1>
{% if errer_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question.id %}" method="post">
{% csrf_token %}
{% for choice in question.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>
part of def vote in mysite/polls/views.py
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):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'question': question,
'error_message': "You didn't select a choice.",
})
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('polls:results', args=(question.id,)))
error
NoReverseMatch at /polls/1/
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
Request Method: GET
Request URL: http://127.0.0.1:8000/polls/1/
Django Version: 3.0.7
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
Exception Location: C:\Users\hdh45\crawling_practice\firstP\venv\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677
Python Executable: C:\Users\hdh45\crawling_practice\firstP\venv\Scripts\python.exe
Python Version: 3.8.3
Error during template rendering
In template X:\python\practice_well\polls\templates\polls\detail.html, error at line 5
I guess vote url isnt work. maybe something wrong. but i dont know exact anwser. My googling power is useless.. help me.
<form action="{% url '***polls***:vote' question.id %}" method="post">
polls was a string and your urls.py in a
path('**<int:question_id>**/vote/', views.vote, name='vote')
<int:question_id> is a int. i think that's a mistake
and I'm also begginer

NoReverseMatch at /polls/ Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/<int:pk>/']

Attempting to start the server and getting error line like
NoReverseMatch at /polls/
Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: ['polls/<int:pk>/']
my views.py
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.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Question
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
Views for index,results and detail
my urls.py
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url('', views.IndexView.as_view(), name='index'),
url(r'^<int:pk>/', views.DetailView.as_view(),name='detail'),
url(r'^<int:pk>/results/', views.ResultsView.as_view(), name='results'),
url(r'^<int:question_id>/vote/', views.vote, name='vote'),
]
my index.html
{% 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 %}
I have tried many time but i didn't got a solution please help me out.
You are mixing up the url() syntax (which uses regexes), and the new path() syntax in Django 2.0+.
Make sure your are using the tutorial which matches your Django version (e.g. Django 2.1 or e.g. Django 1.11), then make sure your urls.py exactly matches the code in the tutorial.
For people who use regex, something like this below will work;
url(r'^((?P<pk>\d+))/$', views.DetailView.as_view(),name='detail'),

Django template doesn't load

Am following the Django Website's tutorial, currently on Pt3(https://docs.djangoproject.com/en/1.11/intro/tutorial03/)
Tutorial states: "This code should create a bulleted-list containing the “What’s up” question from Tutorial 2. The link points to the question’s detail page."
After adding the template and running the server I still only see this
previous page and no updated template
, what's wrong here? Thanks for your help!
django_proj/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),
]
django_proj/mysite/polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
#ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>[0-9]+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
django_proj/mysite/polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = {
'latest_question_list': latest_question_list,
}
return HttpResponse(template.render(context, request))
def detail(request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "You're looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
def index(request):
return HttpResponse("At Polls Index")
/django_proj/mysite/polls/templates/polls/index.html
{% 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 %}
Similar problem to: Django Template not loading
In views.py remove this, coz you have defined it 2 times.
def index(request):
return HttpResponse("At Polls Index")

How do I fix this NoReverseMatch in Django? [duplicate]

This question already has an answer here:
Unexpected NoReverseMatch error when using include() in urls patterns
(1 answer)
Closed 5 years ago.
Edit: this question is different from django 1.8 NoReverseMatch at error because this one specifically asks how to do it with the ModelViewSet class
I'm trying to make a blog post/facebook wall type app and am getting a NoReverseMatch Error in Django. It happens after trying to submit the post form.
Here's my views.py
from django.shortcuts import render, get_object_or_404, redirect
from wall.models import Post
from .forms import PostForm
def index(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'wall/index.html', {'form': form})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'wall/post_detail.html', {'post': post})
urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^post_detail/(?P<pk>\d+)/$', views.post_detail, name='post_detail'),
]
post_detail.html
{% extends 'blog/base.html' %}
{% block content %}
<div class="post">
{% if post.published_date %}
<div class="date">
{{ post.published_date }}
</div>
{% endif %}
<p>{{ post.text|linebreaksbr }}</p>
</div>
{% endblock %}
The error page says
Reverse for 'post_detail' with keyword arguments '{'pk': 5}' not found
1 pattern(s) tried: ['$post_detail/(?P<pk>\\d+)/$']
I've looked at this answer already, but none of the suggestions help. My regex and url names are all spelled correctly.
How do I fix this error?
Here is my base urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', include('wall.urls'), name='index'),
url(r'^accounts/register/$', views.register, name='register'),
url(r'^accounts/register/complete/$', views.registration_complete, name='registration_complete'),
url(r'^accounts/login/$', auth_views.login, name='login'),
url(r'^accounts/logout/$', auth_views.logout, name='logout'),
url(r'^accounts/loggedin/$', views.logged_in, name='loggedin'),
]
I think your issue is on the redirect after the form submission, change
return redirect('post_detail', pk=post.pk)
to
return redirect(reverse('post_detail', kwargs={'pk': post.pk}))
(to import reverse use : from django.core.urlresolvers import reverse)
As Alasdair pointed out, a $ on include was also missing from your base urls.py
It looks as if you have a dollar in your regex when you include your app's urls. Remove it.

Django Tutorial Part 3 - Index.html not doing anything

I am working on part 3 of the django tutorial and after setting up index.html and views although nothing is happening.
This is what the tutorial says should be happening, "Load the page by pointing your browser at “/polls/”, and you should see a bulleted-list containing the “What’s up” question from Tutorial 1. The link points to the question’s detail page."
The list doesn't show up, all I see if "Hello, world. You're at the polls index."
These are my files:
from django.http import HttpResponse
from django.shortcuts import render
from polls.models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
context = {'latest_question_list': latest_question_list}
return render(request, 'polls/index.html', context)
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
def detail (request, question_id):
return HttpResponse("You're looking at question %s." % question_id)
def results(request, question_id):
response = "Your looking at the results of question %s."
return HttpResponse(response % question_id)
def vote(request, question_id):
return HttpResponse("You're voting on question %s." % question_id)
Views.py
{% 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 %}
Index.Html (located in mysite/polls/templates/polls)
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
# ex: /polls/
url(r'^$', views.index, name='index'),
# ex: /polls/5/
url(r'^(?P<question_id>\d+)/$', views.detail, name='detail'),
# ex: /polls/5/results/
url(r'^(?P<question_id>\d+)/results/$', views.results, name='results'),
# ex: /polls/5/vote/
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
)
Urls.py
I'm not sure why nothing is happening, what I may be doing wrong. Any suggestions? Thanks!
The problem is you have more than one index method. The first one looks good, but the second one is replacing the behavior of the first one.

Categories

Resources