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
Related
http://127.0.0.1:8000/tasks works fine but when when I add a task and submit it, I get a 404 thrown at me,
ERROR: Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
admin/
polls/
newyear/
tasks/ [name='index']
tasks/ add [name='add']
The current path, tasks/{ % url 'add' % }, didn't match any
of these
mysite\tasks\urls.py
from django.urls import path,include
from . import views
urlpatterns = [
path("", views.index, name='index'),
path("add", views.add, name='add')]
mysite\mysite\urls.py
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('polls/',include('polls.urls')),
path('newyear/', include('newyear.urls')),
path('tasks/', include('tasks.urls'))]
mysite\tasks\views.py
from django.shortcuts import render
tasks = ["foo", "bar", "baz"]
def index(request):
return render(request, "tasks/index.html", {
"tasks": tasks
})
def add(request):
return render(request, "tasks/add.html")
)
mysite\tasks\templates\tasks\index.html
{% extends "tasks/layout.html" %}
{% block body %}
<h1>
Tasks
</h1>
<ul>
{%for task in tasks%}
<li> {{task}}</li>
{%endfor%}
</ul>
Add a New Task
{% endblock %}
mysite\tasks\templates\tasks\add.html
{% extends "tasks/layout.html" %}
{% block body %}
<h1>
Add Task
</h1>
<form action= "{ % url 'add' % }" method="post">
<input type="text" name="task">
<input type="submit">
</form>
View Tasks
{% endblock %}
Aside from Alexey Popov's answer to fix broken tags with space {% ... %}, also remember to add within your form a csrf token:
<form action= "{% url 'add' %}" method="post">
{% csrf_token %}
...
Python/Django beginner here - I get this error:
Reverse for 'topic' with arguments '('',)' and keyword arguments '{}'
not found. 1 pattern(s) tried: ['topics/(?P\d+)/$']
when trying to load my template.
This is my template:
{% extends "learning_logs/base.html" %}
{% block content %}
<p>Topics</p>
<ul>
{% for topic in topics %}
<li>
{{ topic }}
</li>
{% empty %}
<li>No topics for now</li>
{% endfor %}
</ul>
{% endblock content %}
This is my views.py
from django.shortcuts import render
from .models import Topic
# Create your views here.
def index(request):
'''Home page for learning log'''
return render(request, 'learning_logs/index.html')
def topics(request):
'''Show all topics'''
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context)
def topic(request, topic_id):
'''Show a single topic and all its entries'''
topic = Topic.objects.get(id=topic_id)
entries = topic.entry_set.order_by('-date_added')
context = {'topic': topic, 'entries': entries}
return render(request, 'learning_logs/topic.html', context)
I have been on this a while now, read some previous answers here, but they all had to do with auth/login not working. Also tried removing the '' after the url as some answers suggested but it didnt work. I am using Python Crash Course: A Hands-On, Project-Based Introduction to Programming for my tutorials.
Any help will be appreciated.
Finally, this is my urls.py code
from django.conf.urls import url
from . import views
urlpatterns = [
# Home page
url(r'^$', views.index, name='index'),
url(r'^topics/$', views.topics, name='topics'),
url(r'^topics/(?P<topic_id>\d+)/$', views.topics, name='topic'),
According to the error, there was an argument passed into the url tag, but it was empty:
Reverse for 'topic' with arguments '('',)'...
That's because of the topic_id variable, it is not defined. You should use topic.id instead:
{{ topic }}
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.
I am working on extending the webapp we're left off with after completing the official Django Tutorial.
One of the functionalities I am looking to add is the ability for users to add polls themselves.
I am struggling with getting the page to process the data and then redirect to the index page ('/polls').
When I submit a new poll as a logged in user, I am returned to my index page, which is supposed to show most recently published polls, or in the event of no polls, the message "No polls are available."
For some reason, I always see "No polls are available", but once I click to the index page via a link on the site, it displays all of my polls, including my most recently created one, data intact!
Any thoughts here? I think I have included the relevant info below but happy to supply more. Thanks in advance for any help/advice.
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 Poll.objects.order_by('-pub_date')[:15]
#login_required
def add_poll(request):
ChoiceFormSet = formset_factory(ChoiceForm, extra=3, min_num=2, validate_min=2)
if request.method == 'POST':
form = PollForm(request.POST)
formset = ChoiceFormSet(request.POST)
if all([form.is_valid(), formset.is_valid()]):
poll = form.save()
for inline_form in formset:
if inline_form.cleaned_data:
choice = inline_form.save(commit=False)
choice.question = poll
choice.save()
return render(request, 'polls/index.html', {})
else:
form = PollForm()
formset = ChoiceFormSet()
return render(request, 'polls/add_poll.html', {'form': form, 'formset': formset})
add_poll.html
{% extends 'polls/base.html' %}
{% block title %}Add Poll{% endblock %}
{% block body_block %}
<form role="form" id="poll_form" method="post" action="{% url 'polls:add_poll' %}">
<h2 class="form-signin-heading">Add a Poll</h2>
{% csrf_token %}
<table>
{{ form }}
{{ formset }}
</table>
<br/>
<button class="btn btn-primary" type="submit" name="submit">Create Poll</button>
</form>
{% endblock %}
index.html
{% extends 'polls/base.html' %}
{% block body_block %}
{% if latest_question_list %}
<ul>
{% for poll in latest_question_list %}
<li>{{ poll.question_text }}</li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
{% endblock %}
urls.py
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns('',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^(?P<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
url(r'^(?P<pk>\d+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^add_poll/$', views.add_poll, name='add_poll'),
url(r'^(?P<question_id>\d+)/vote/$', views.vote, name='vote'),
url(r'^profile_page/$', views.ProfileView.as_view(), name='profile_page'),
url(r'^edit_profile/$', views.edit_profile, name='edit_profile'),
)
When you save your form you are not redirecting.
Your are returning 'polls/index.html' with empty polls data, that's why you always get "No polls are available". But this is very incorrect, you must follow the Post/Redirect/Get (PRG) pattern, so instead of:
return render(request, 'polls/index.html', {})
do this:
return HttpResponseRedirect(reverse('polls:index'))
You don't do any redirect right now, you are just rendering your index template with an empty context (that's why you don't see anything). To redirect, you need to use HttpResponseRedirect when your form is valid.
So, please change line:
return render(request, 'polls/index.html', {})
(just over the else) to
return HttpResponseRedirect(reverse('index'))
I finally figured it out. I had to change my html form to this:
<form method="POST" action="{% url 'new_beam:beam_diagram' beam_id=1 %}" enctype="multipart/form-data">
I'm creating this django app using the tutorial and i'm up to part 4 https://docs.djangoproject.com/en/dev/intro/tutorial04/
The app display a basic poll and when you click on it , it display some choices and a button to vote.
The problem is when I click on vote . It display Page not found.
I think the problem is the redirection but I don't know where to pin point the problem.
The first page is the index.html which display the questions then it's the detail.html which display the choices and question. I know when I click on vote , it goes back to the app URLconf then the urlconf execute the view function and the view function execute the results.
My detail.html are
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="/myapp/{{ poll.id }}/vote/" method="post">
{% 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>
My urls.py inside myapp are :
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 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 results.html are:
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>
Vote again?
Thank you for helping me . This will be my first breakthrough app if I can get this to work.
My Main URLconf is :
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'^admin/', include(admin.site.urls)),
)
Don't hardcode urls
You should not hardcode a URL anywhere - just like for file system paths. You're not only killing kittens but also making your code less solid !
Reverse urls instaed !
Read about reversing urls for starters, and using named urls for main dish, and about {% url %} templatetag for dessert.
At the time of digestive, you will be a master of Django url system B)
Read the tutorial
In the tutorial you linked, they don't hardcode urls:
{% url 'polls:vote' poll.id %}
That's the way to go !!
Make sure you don't have a hardcoded url anywhere in your templates and your problem will go away.
Loose the myapp bit of the form action.
It should be
<form action="polls/{{poll.id}}/vote" method="post">
This matches the regex in your urls.py file -
url(r'^polls/', include('myapp.urls')),
and then in myapp.urls -
url(r'^(?P<poll_id>\d+)/vote/$', 'vote'),
The include function means that django is trying to match ^polls/(?P<poll_id>\d+)/vote/$
If you look at the error page your getting you can see the url's that django's trying to match against (none of them contain 'myapp' it should be polls).
IMPORTANT
When you get further on in the tutorial you'll see that you shouldn't be hardcoding urls in your templates (as jpic rightly points out). At this stage you need to swap out the form action for {% url 'polls:vote' poll.id %}.