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.
Related
Views.py
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from . models import Question
from django.template import loader, RequestContext
# Create your views here.
def index(request):
latest_questions = Question.objects.all()[:5]
context = {'latest_questions': latest_questions}
return render(request, 'polls/index.html', context)
def detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
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():
return render(request, 'polls/detail.html', {'question': question, 'error_message' : "Please select a choice"})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
I get this no reverse match for results dues it not being a valid view function. I am new to django. How can I solve this?Does it mean there's an issue with my view.py code or what could be the issue as I am following a tutorial.
polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns=[
url(r'^$', views.index,name='index'),
url(r'^(?P<question_id>[0-2]+)/$', views.detail, name='detail'),
url(r'^(?P<question_id>[0-2]+)/results', views.results, name='result'),
url(r'^(?P<question_id>[0-2]+)/votes', views.vote, name='vote'),
]
This is the polls/templates/polls/results.html file
Results.html
{% extends 'polls/base.html' %}
{% block main_content %}
<h1>{{question.question_text}}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li> {{choice.choice_text}} -- {{choice.votes}} vote{{ choice.votes|pluralize}}</li>
{% endfor %}
</ul>
Vote Again?
{% endblock %}
This mysite/urls.py where I used namespace there. What could be the issue.
Mysite/urls.py
from django.contrib import admin
from django.conf.urls import url, include
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include(('polls.urls', 'polls'), namespace='polls')),
]
You have used reverse in the view: vote. Change the first argument from "polls:results" to "polls:result" or "result".
Reverse is used to point to a URL pattern defined in urls.py. Look at the third entry in your urlpatterns, you have provided name "result" to it.
That should solve your problem.
hi guys I can't load polls/detail.html
I am currently studying Django tutorials part3
If I enter http: // localhost: 8000 / polls / index.html in the browser address bar, I get a page not found response
and The browser shows me the following text
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
polls/ [name='index']
polls/ <int:question_id>/ [name='detail']
polls/ <int:question_id>/results/ [name='results']
polls/ <int:question_id>/vote/ [name='vote']
admin/
The current path, polls/index.html, didn't match any of these
I think there's a problem with the route
this is my view.py code
from django.shortcuts import get_object_or_404, render
from .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 detail(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/detail.html', {'question': question})
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)
polls/tamplates/polls/detail.html
<h1>{{ question.question_text }}</h1>
<ul>
{% for choice in question.choice_set.all %}
<li>{{ choice.choice_text }}</li>
{% endfor %}
</ul>
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 %}
You can't access the index.html file directly by entering http://localhost:8000/polls/index.html because Django app doesn't work that way.
In Django we map routes, pattern of urls to corresponding view. When request comes to that url, the corresponding view is rendered.
These are the routes/urls defined by your router/urls mapper:
polls/ [name='index']
polls/ <int:question_id>/ [name='detail']
polls/ <int:question_id>/results/ [name='results']
polls/ <int:question_id>/vote/ [name='vote']
admin/
When request come to :
/polls/ : First pattern matched and it's corresponding view is returned which internally calls and render index.html
/polls/1/ : When you append question id, second pattern is matched and the detail view is called
/polls/1/results/ : When you append results also the result is rendered
and so on.
So you can't simply access index.html at http://localhost:8000/polls/index.html
It will only be served at the url pattern mapped to it. Which I think here is /polls/ whose namespace is index
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")
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.
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.