This refers to the django 1.6 tutorial.
I keep getting this error message when I try to open the /polls/1/ page in part 4 of the tutorial:
NoReverseMatch at /polls/1/
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<poll_id>\\d+)/vote/$']
Request Method: GET
Request URL: http://*/polls/1/
Django Version: 1.6.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'vote' with arguments '('',)' and keyword arguments '{}' not found. 1 pattern(s) tried: [u'polls/(?P<poll_id>\\d+)/vote/$']
Exception Location: /home/iamal/lib/python2.7/Django-1.6.4-py2.7.egg/django/core/urlresolvers.py in _reverse_with_prefix, line 452
Python Executable: /package/host/localhost/python-2.7.3/bin/python
Python Version: 2.7.3
Python Path:
['/home/iamal/tutorial',
'/home/iamal/bin',
'/home/iamal/lib/python2.7/Django-1.6.4-py2.7.egg',
'/home/iamal/lib/python2.7/gunicorn-19.1.1-py2.7.egg',
'/package/host/localhost/python-2.7.3/lib/python2.7/site-packages/MySQL_python-1.2.3-py2.7-linux-x86_64.egg',
'/package/host/localhost/python-2.7.3/lib/python2.7/site-packages/distribute-0.6.35-py2.7.egg',
'/package/host/localhost/python-2.7.3/lib/python27.zip',
'/package/host/localhost/python-2.7.3/lib/python2.7',
'/package/host/localhost/python-2.7.3/lib/python2.7/plat-linux2',
'/package/host/localhost/python-2.7.3/lib/python2.7/lib-tk',
'/package/host/localhost/python-2.7.3/lib/python2.7/lib-old',
'/package/host/localhost/python-2.7.3/lib/python2.7/lib-dynload',
'/package/host/localhost/python-2.7.3/lib/python2.7/site-packages',
'/home/iamal/lib/python2.7']
Server time: So, 11 Jan 2015 00:03:43 +0100
I noticed that there seems to be no argument to be passed in the error message. When I replaced poll.id from line 5 in the details.html with '1', it works. I have also checked that I included namespace="polls" in the project/urls.py file which seems to have been a common issue.
My details.html:
<h1>{{ poll.question }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:vote' poll.id %}" 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 polls/views.py:
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.template import Context, loader
from django.core.urlresolvers import reverse
from polls.models import Poll, Choice
def index(request):
latest_poll_list = Poll.objects.order_by('-pub_date')[:5]
context = {'latest_poll_list': latest_poll_list}
return render(request, 'polls/index.html', context)
def detail(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/detail.html', {'poll': poll_id})
def results(request, poll_id):
poll = get_object_or_404(Poll, pk=poll_id)
return render(request, 'polls/results.html', {'poll': poll})
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):
return render(request, 'polls/detail.html', {
'poll': 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,)))
Your detail view is passing the poll_id to the template target instead of the poll object itself. It should be:
return render(request, 'polls/detail.html', {'poll': poll})
Related
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
I have been following this Django tutorial, and I am trying to remove hardcoded URLs, but I can't make the reverse function work.
That's my detail view:
def detail(request, question_id):
try:
question = Question.objects.get(pk=question_id)
except Question.DoesNotExist:
raise Http404("Question does not exist")
# How it was before:
# return render(request, 'polls/detail.html', {'question': question})
return HttpResponse(reverse('polls:detail', kwargs={'question': question}))
path('<int:question_id>/', views.detail, name='detail')
This is the urls.py:
app_name = 'polls'
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
And this is the template for the detail view:
<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" />
Index
</form>
Can somebody help me with that or give any tips?
Thanks in advance.
I think your original code was fine. If you were in another view (say, the vote view) and wanted to redirect the user to the detail view, you could do this:
return HttpResponseRedirect(reverse('polls:detail', args=(question.id,)))
Copied from part 4 of the tutorial: https://docs.djangoproject.com/en/2.0/intro/tutorial04/#write-a-simple-form:
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,)))
The last line redirects the user from the vote view to the results view and uses reverse() to avoid hard-coding the url.
I have made a web site by seeing django tutorial. https://docs.djangoproject.com/en/1.11/intro/
I got an error
AttributeError at /polls/1/
'method' object has no attribute 'inner_html' .
Traceback says
Traceback:
File "/Users/XXX/django/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
130. response = self.process_exception_by_middleware(e, request)
File "/Users/XXX/django/django/core/handlers/base.py" in _get_response
128. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/Users/XXX/djangostudy/polls/views.py" in detail
40. form = VoteForm(question=obj)
File "/Users/XXX/djangostudy/polls/forms.py" in __init__
21. self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}<br>'
Exception Type: AttributeError at /polls/1/
Exception Value: 'method' object has no attribute 'inner_html'
My forms.py is like
from django import forms
class MyForm(forms.Form):
text = forms.CharField(max_length=100,required=False,label='テキスト')
class VoteForm(forms.Form):
choice = forms.ModelChoiceField(
queryset=None,
label='選択',
widget=forms.RadioSelect,
empty_label=None,
error_messages={
'required':"You didn't select a choice.",
'invalid_choice':"invalid choice.",
},
)
def __init__(self,question,*args,**kwargs):
super().__init__(*args,**kwargs)
self.fields['choice'].queryset = question.choice_set.all()
self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}<br>'
Setting of radio button is written in detail.html,like
<!DOCTYPE html>
<h1>{{ question.question_text }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'poll_vote' question.id %}" method="post">
<!--<form action="" 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 %}
<!--{{ form }}-->
<input type="submit" value="Vote" />
</form>
</html>
views.py is
from django.shortcuts import render
from django.utils.html import mark_safe
from .models import Question
from django.http import HttpResponse
from django.shortcuts import Http404
from django.shortcuts import get_object_or_404,redirect
from .models import Choice
from django.views.generic import TemplateView
from django.views.generic import DetailView
from django.views.generic import ListView
from .forms import MyForm
from .forms import VoteForm
# Create your views here.
def index(request):
return render(request,'polls/index.html',{
'questions': Question.objects.all(),
})
def detail(request,pk):
obj = get_object_or_404(Question,pk=pk)
if request.method == "POST":
form = VoteForm(question=obj,data=request.POST)
if form.is_valid():
return redirect('polls:results',pk)
else:
form = VoteForm(question=obj)
return render(request,'templates/polls/detail.html',{
'form':form,
'question': obj,
})
def vote(request,pk):
pass
def results(request,pk):
obj = get_object_or_404(Question,pk=pk)
return render(request,'polls/results.html',{
'question':obj,
})
def form_test(request):
if request.method == "POST":
#request.POST???
form = MyForm(data=request.POST)
if form.is_valid():
pass
else:
form = MyForm()
return render(request,'polls/form.html',{
'form':form,
})
I do not know how to fix it.I cannot understand why this error happen. WHat should I do to fix this?
The tutorial had inner_html,so I think it is necessary to do something needed.But,is it useless?
I wanna show the page like
in this part
self.fields['choice'].widget.render.inner_html = '{choice_value}{sub_widgets}'
I wanna make this page is radio button page.
I'm receiving the following error
Error: Reverse for placeinterest with arguments ('',) and keyword arguments {} not found. 1 pattern(s) tried:
[u'polls/(?P<section_id>[0-9]+)/placeinterest/$']
I worked through the Django example for a polling app, and now I'm trying to create a class registration app adapting what I already have. Error points to line 5 here:
<h1>{{ section.class_name }}</h1>
{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
<form action="{% url 'polls:placeinterest' section.id %}" method="post">
{% csrf_token %}
<input type="radio" name="incr" id="incr" value="incr" />
<label for="incr"></label><br />
<input type="submit" value="Placeinterest" />
</form>
But I think the problem is in my placeinterest function:
def placeinterest(request, section_id):
section = get_object_or_404(Section, pk=section_id)
try:
selected_choice = section.num_interested
except (KeyError, Section.num_interested.DoesNotExist):
# Redisplay the question voting form.
return render(request, 'polls/detail.html', {
'section': section,
'error_message': "You didn't select a choice.",
})
else:
section.num_interested += 1
section.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=(section.id,)))
I'm not sure what my POST call should be if my Section class looks like this:
class Section(models.Model):
class_name = models.CharField(max_length=200)
num_interested = models.IntegerField(default=0)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.class_name
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(minutes=3)
def some_interested(self):
if self.num_interested > 0:
return "There is currently interest in this class"
else:
return "There is currently no interest in this class"
The results part comes up fine in my browser, and here is urls.py for good measure:
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<section_id>[0-9]+)/placeinterest/$', views.placeinterest, name='placeinterest'),
]
Edit: adding the original code from the example in hopes that might help someone see where I went wrong:
urls:
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'),
]
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()
# 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, where I'm having problems after making my changes:
<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 error has nothing to do with your view. It specifically says it's trying to match the URL named placeinterest in the error. It knows the URL exists, but the arguments are wrong.
It thinks you're trying to pass an empty string as a positional argument. This means that section.id is probably None when the template is rendered. It's converting the null value into an empty string and passing it as a positional argument, hence ('',). That's a tuple with one empty string value in it.
The problem is here:
<form action="{% url 'polls:placeinterest' section.id %}" method="post">
Django can't figure out the url argument as it's misconfigured. Use this:
<form action="{% url 'polls:placeinterest' section_id=section.id %}" method="post">
You also need to ensure that section id is valid a number (be careful of what you supply as "section" as your context.
I'm building a little web server using django but I keep getting 'str' object has no attribute 'regex' in my template where it says {% url 'signup' %} and {% url 'login' %}. I guess this will be something to do with URL binding, or probably me not having imported the right module that is needed to refer to a URL by its name attribute. But I can't figure a way around this. Thanks in advance.
Template
{% include "header.html" %}
<div class="container">
<div class="page-header"><h3>로그인</h3></div>
<form method="post" action="{% url 'login' %}" role="login">
{% csrf_token %}
<div class="form-group">
<label>아이디</label>
<input type="text" name="username" placeholder="아이디를 입력하세요" class="form-control" />
</div>
<div class="form-group">
<label>비밀번호</label>
<input type="password" name="password" placeholder=" 암호를 입력하세요" class="form-control" />
<input type="hidden" name="next" value="/" />
</div>
<div class="form-group">
<div class="btn-group pull-right">
<input type="submit" value="로그인" class="btn btn-primary"/>
가입하기
</div>
</div>
</form>
</div>
{% include "footer.html" %}
Views.py
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from docx import Document
from exam.models import *
def login(request):
return render(request, 'login.html')
def signup(request):
try:
if request.session["error"]:
error_message = request.session["error"]
del request.session["error"]
except KeyError:
error_message = None
context = {
"error_message" : error_message
}
return render(request, "signup.html", context)
def signup_submit(request):
try:
username = request.POST["username"].strip()
password = request.POST["password"].strip()
password_confirm = request.POST["password_confirm"].strip()
full_name = request.POST["full_name"].strip()
student_num = request.POST["student_num"].strip()
if username and password and password_confirm and full_name and student_num:
user = User(username=username, full_name=full_name, student_num=student_num)
user.set_password(password)
user.save()
return redirect("index")
except KeyError:
request.session["error"] = "올바른 요청이 아닙니다."
return redirect("signup")
else:
request.session["error"] = "입력한 정보가 올바르지 않습니다."
return redirect("signup")
URLS.py
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'django.contrib.auth.views.login', {'template_name': 'login.html'}, name='login'),
url(r'^signup/$', 'exam.views.signup', name='signup'),
url(r'^signup/submit/$', 'exam.views.signup_submit', name='signup_submit'),
Error Traceback:
AttributeError at /
'str' object has no attribute 'regex'
Request Method: GET
Request URL: http://192.168.56.101:8000/
Django Version: 1.7.6
Exception Type: AttributeError
Exception Value:
'str' object has no attribute 'regex'
Exception Location: /home/web/venv/lib/python3.4/site-packages/django/core/urlresolvers.py in _populate, line 282
Python Executable: /home/web/venv/bin/python