NoReverseMatch at - django polls app tutorial - python

I keep getting this when trying to load da page:
NoReverseMatch at /polls/
Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<question_id>[0-9]+)/vote/$']
In template C:\Users\sarah\Desktop\django2\myproject\my_site\polls\templates\polls\index.html, error at line 20
line 20:
<form action="{% url 'polls:vote' question.id %}" method="post">
I am a complete beginner at django, css, html, ... I kept checking in with the tutorial, comparing my code with the code reference in the tutorial, however I see no mistake.
My index.html:
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}">
{% 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 %}
<h1>{{ question.question_text }}</h1>
{% if error_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>
The vote function in 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()
return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
urls.py:
from django.urls import path
from . import views
app_name = 'polls'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
Thank you.

The main reason here is you are using your index.html with the form where you should really have this in polls/detail where you have access to a question object by pk. Right now you are trying to access the id property of question but question is undefined in your index.html.
Place the following in your polls/details.html
<h1>{{ question.question_text }}</h1>
<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>
Then, navigate to polls/1 or whatever question.id you want and then try and use the form.

Related

Django Polls Project: Reverse for 'polls.index' not found

I'm trying to finish my Django Polls Project from the Django Documentation but I ran into the "Reverse for 'polls.index' not found. 'polls.index' is not a valid view function or pattern name." error.
The full error details can be seen here
The following are my files.
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
crossorigin="anonymous"
/>
<title>Pollster {% block title %}{% endblock %}</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 m-auto">
{% block content %}{% endblock %}
</div>
</div>
</div>
</body>
</html>
index.html
{% extends 'base.html' %}
{% block content %}
<h1 class="text-center mb-3">Poll Questions</h1>
{% if latest_question_list %}
{% for question in latest_question_list %}
<div class="card mb-3">
<div class="card-body">
<p class="lead">{{ question.question_text}}</p>
Vote Now
Results
</div>
</div>
{% endfor %}
{% else %}
<p>No polls available</p>
{% endif %}
{% endblock %}
mysite.urls
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('polls/', include('polls.urls')),
path('admin/', admin.site.urls),
]
polls.urls
from django.urls import path
from . import views #from ALL import views
app_name = 'polls'
urlpatterns = [
path('', views.index, name='index'),
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'),
]
polls.views
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from .models import Question, Choice
# Get questions and display them
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)
# Show specific question and choices
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
return render(request, 'polls/detail.html', {'question': question})
# Get question and display results
def results(request, question_id):
question = get_object_or_404(Question, pk=question_id)
return render(request, 'polls/results.html', {'question': question})
# Vote for a question choice
def vote(request, question_id):
# print (request.POST['choice'])
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,)))
detail.html
{% extends 'base.html' %}
{% block content %}
Back To Polls
<h1 class="text-center mb-3">{{ question.question_text }}</h1>
{% if error_message %}
<p class="alert alert-danger">
<strong>{{ error_message }}</strong>
</p>
{% endif %}
<form action="{% url 'polls:vote' question.id %}" method ="post">
{% csrf_token %}
{% for choice in question.choice_set.all %}
<div class="form-check">
<input type="radio" name="choice" class="form-check-input" id="choice{{ forloop.counter }}" value = "{{ choice.id }}"/>
<label for="choice{{ forloop.counter }}">
{{ choice.choice_text }}
</label>
</div>
{% endfor %}
<input type="submit" value ="Vote" class ="btn btn-success btn-lg btn-block mt-4" />
</form>
{% endblock %}
I am new to Django and I would like to learn methods to find out where the errors could be originating from. I checked the code in reference with this finished project from the channel I'm watching but couldn't find the error I made.
Where could the error in my code be?
I researched and this stackoverflow question might be the same as mine but was not solved as well.
Here is my folder structure
I am also new to python for web development so any tips on how I could study this would be helpful. Thank you in advanced!

error during django template rendering

working in django tutorials and this error in template rendering appears
NoReverseMatch at /music/1/ Reverse for 'favorite' with arguments
'(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
this is a detailed view for the problem
Error during template rendering
In template E:\Codes\bucky - Django Tutorials for Beginners\website\music\templates\music\detail.html, error at line 10
Reverse for 'favorite' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []
1 <img src="{{ album.album_logo }}">
2
3 <h1>{{ album.album_title }}</h1>
4 <h2>{{ album.artist }}</h2>
5
6 {% if error_message %}
7 <p><strong>{{ error_message }}</strong></p>
8 {% endif %}
9
10 <form action="{% url 'music:favorite' album.id %}" method="post">
11 {% csrf_token %}
this is my music/urls.py
app_name = 'music'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<album_id>[0-9]+)/$', views.detail ,name='detail'),
url(r'^(?P<album_id>[0-9]+)/favorite/$', views.favorite ,name='favorite'),
]
the detail.html file where the error appear in the form
<img src="{{ album.album_logo }}">
<h1>{{ album.album_title }}</h1>
<h2>{{ album.artist }}</h2>
{% if error_message %}
<p><strong>{{ error_message }}</strong></p>
{% endif %}
<form action="{% url 'music:favorite' album.id %}" method="post">
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{ forloop.counter }}" name="song" value="{{ song.id }}">
<label for="song{{ forloop.counter }}">
{{ song.song_title }}
{% if song.is_favorite %}
<img src="http://i.imgur.com/b9b13Rd.png">
{% endif %}
</label>
<br>
{% endfor %}
<input type="submit" value="Favorite">
</form>

NoReverseMatch at /polls/1/vote/ when following Django's official tutorial

I'm following the Django tutorial. I've reached part 4, at the moment of building the vote form. Sadly, I cannot find the problem that is causing the following error:
NoReverseMatch at /polls/1/vote/
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P[0-9]+)/vote/$']
Both /polls/1/vote and /polls/1/ throw the error above.
My polls/urls.py
from django.conf.urls import url
from . import views
app_name = 'polls'
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<question_id>[0-9]+)/$', views.details, name='details'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.results, name='results'),
url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, name='vote'),
]
And here's the details.html, which shows the error at line 11, the form opening tag:
<h1>{{ question.question }}</h1>
{% if error %}
<p>
<strong>
{{ error }}
</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 }}</label>
<br/>
{% endfor %}
<input type="submit" value="Vote">
</form>

NoReverseMatch Django Tutorial 1.8

so I started on the generic views section of the tutorial, until which point everything was smooth sailing, working perfectly and then I get this error:
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P[0-9]+)/vote/$']
Here is my 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'),
]
And here is my views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext, loader
from django.http import Http404
from .models import Choice, Quesion
from django.core.urlresolvers import reverse
from django.views import generic
# Create your views here.
class IndexView(generic.ListView):
template_name = 'polls/index.html'
context_object_name = 'latest_question_list'
def get_queryset(self):
return Quesion.objects.order_by('-pub_date')[:5]
class DetailView(generic.DetailView):
model = Quesion
template_name = 'polls/detail.html'
class ResultsView(generic.DetailView):
model = Quesion
template_name = 'polls/results.html'
def vote(request, question_id):
p = get_object_or_404(Quesion, 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':"No choice selected",
})
else:
selected_choice.votes += 1
selected_choice.save()
return HttpResponseRedirect(reverse('polls:results',args=(p.id,)))
And here is my detail.html
<h1>{{ question.question_text }}</h1>
{% if error_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_txt }} </label><br />
{% endfor %}
<input type="submit" value="vote" />
</form>
You have two problems. The first is that DetailView doesn't provide a question variable in the template, but provides one called object instead. So all instances of question in the template needs to be changed to object.
Secondly, the URL is expecting a keyword argument question_id, but you're passing a non-keyword argument to the {% url %} tag. You need to change that to say question_id=object.id. Your detail.html should look like this:
<h1>{{ object.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' question_id=object.id %}" method="post">
{% csrf_token %}
{% for choice in object.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice_txt }} </label><br />
{% endfor %}
<input type="submit" value="vote" />
</form>

Use Custom DB for Login in Django [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am very new to django, I have an sqlite3 database file and I want to use a table in it for authentication of my website, It is a very basic html login page, How can I do that? Also if you can tell me how the built-in login and authenticate work and which DB to they use?Thanks in advance.
Please read this https://docs.djangoproject.com/en/dev/topics/auth/ and http://www.djangobook.com/en/2.0/chapter14/ for better understanding.
To achieve basic login functionality in Django you can follow below steps.
Prerequisite: *You must have valid DB setting in your settings.py*
1.Urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# index page
url(r'^$', 'app.views.index'),
# after login user will be redirected to this url
url(r'^logged_in/$', 'app.views.logged_in'),
# using default django auth views with custom templates
url(r'^login/$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}),
url(r'^logout/$', 'django.contrib.auth.views.logout', {'template_name': 'logout.html'}),
)
2. Views.py
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.template import RequestContext
# index view (just redirect to login page)
def index(request):
return HttpResponseRedirect('/login')
# this view will run after successfull login
#login_required
def logged_in(request):
return render_to_response('logged_in.html', context_instance=RequestContext(request))
3. login.html
{% extends 'base.html' %}
{% block title %}Log in{% endblock %}
{% block extrastyle %}
<link rel="stylesheet" type="text/css" href="{{ STATIC_URL }}bootstrap/css/signin.css" />
{% endblock %}
{% block content %}
<form action="" class="form-signin" method="post">{% csrf_token %}
<h3 class="form-signin-heading text-center">Please log in</h3>
{% if form.non_field_errors %}
<div class="alert alert-danger">
{{ form.non_field_errors|striptags }}
</div>
{% endif %}
{% if not form.username.errors %}
<input id="id_username" name="username" type="text" class="form-control" placeholder="Username (admin)" autofocus>
{% else %}
<div class="form-group has-error">
{% for error in form.username.errors %}
<label class="control-label" for="id_username">{{ error }}</label>
{% endfor %}
<input id="id_username" name="username" type="text" class="form-control" placeholder="Username (admin)" autofocus>
</div>
{% endif %}
{% if not form.password.errors %}
<input id="id_password" name="password" type="text" class="form-control" placeholder="Password (admin)" autofocus>
{% else %}
<div class="form-group has-error">
{% for error in form.password.errors %}
<label class="control-label" for="id_password">{{ error }}</label>
{% endfor %}
<input id="id_password" name="password" type="text" class="form-control" placeholder="Password (admin)">
</div>
{% endif %}
<button class="btn btn-lg btn-primary btn-block" type="submit">Login</button>
</form>
</form>
{% endblock %}

Categories

Resources