· 7 years ago · May 26, 2018, 03:42 AM
1def vote(request, question_id):
2 try:
3 selected_choice = Question.choice_set.get(pk=request.POST['choice'])
4 except (KeyError, Choice.DoesNotExist):
5 # Redisplay the question voting form.
6 return render(request, 'polls/detail.html', {
7 'question': question,
8 'error_message': "You didn't select a choice.",
9 })
10 else:
11 selected_choice.votes += 1
12 selected_choice.save()
13 # Always return an HttpResponseRedirect after successfully dealing
14 # with POST data. This prevents data from being posted twice if a
15 # user hits the Back button.
16 return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
17
18AttributeError at /polls/1/vote/
19'ReverseManyToOneDescriptor' object has no attribute 'get'
20Request Method: POST
21Request URL: http://localhost:8000/polls/1/vote/
22Django Version: 2.0
23Exception Type: AttributeError
24Exception Value:
25'ReverseManyToOneDescriptor' object has no attribute 'get'
26Exception Location: /Users/coreydickinson/mysite/DJDev/env1/mysite2/mysite3/polls/views.py in vote, line 30
27Python Executable: /Users/coreydickinson/mysite/DJDev/env1/bin/python
28Python Version: 3.6.5
29Python Path:
30['/Users/coreydickinson/mysite/DJDev/env1/mysite2/mysite3',
31 '/Users/coreydickinson/mysite/DJDev/env1/lib/python36.zip',
32 '/Users/coreydickinson/mysite/DJDev/env1/lib/python3.6',
33 '/Users/coreydickinson/mysite/DJDev/env1/lib/python3.6/lib-dynload',
34 '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',
35 '/Users/coreydickinson/mysite/DJDev/env1/lib/python3.6/site-packages']
36Server time: Sat, 26 May 2018 03:16:49 +0000
37
38
39Environment:
40
41
42Request Method: POST
43Request URL: http://localhost:8000/polls/1/vote/
44
45Django Version: 2.0
46Python Version: 3.6.5
47Installed Applications:
48['django.contrib.admin',
49 'django.contrib.auth',
50 'django.contrib.contenttypes',
51 'django.contrib.sessions',
52 'django.contrib.messages',
53 'django.contrib.staticfiles',
54 'polls.apps.PollsConfig']
55Installed Middleware:
56['django.middleware.security.SecurityMiddleware',
57 'django.contrib.sessions.middleware.SessionMiddleware',
58 'django.middleware.common.CommonMiddleware',
59 'django.middleware.csrf.CsrfViewMiddleware',
60 'django.contrib.auth.middleware.AuthenticationMiddleware',
61 'django.contrib.messages.middleware.MessageMiddleware',
62 'django.middleware.clickjacking.XFrameOptionsMiddleware']
63
64
65
66Traceback:
67
68File "/Users/coreydickinson/mysite/DJDev/env1/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
69 35. response = get_response(request)
70
71File "/Users/coreydickinson/mysite/DJDev/env1/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
72 128. response = self.process_exception_by_middleware(e, request)
73
74File "/Users/coreydickinson/mysite/DJDev/env1/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
75 126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
76
77File "/Users/coreydickinson/mysite/DJDev/env1/mysite2/mysite3/polls/views.py" in vote
78 30. selected_choice = Question.choice_set.get(pk=request.POST['choice'])
79
80Exception Type: AttributeError at /polls/1/vote/
81Exception Value: 'ReverseManyToOneDescriptor' object has no attribute 'get'
82
83from django.urls import path
84
85from . import views
86
87app_name = 'polls'
88urlpatterns = [
89 path('', views.IndexView.as_view(), name='index'),
90 path('<int:pk>/', views.DetailView.as_view(), name='detail'),
91 path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
92 path('<int:question_id>/vote/', views.vote, name='vote'),
93]
94
95from django.urls import reverse
96from django.views import generic
97
98from .models import Choice, Question
99
100
101class IndexView(generic.ListView):
102 template_name = 'polls/index.html'
103 context_object_name = 'latest_question_list'
104
105 def get_queryset(self):
106 """Return the last five published questions."""
107 return Question.objects.order_by('-pub_date')[:5]
108
109
110class DetailView(generic.DetailView):
111 model = Question
112 template_name = 'polls/details.html'
113
114
115class ResultsView(generic.DetailView):
116 model = Question
117 template_name = 'polls/results.html'
118
119
120def vote(request, question_id):
121 try:
122 selected_choice = Question.choice_set.get(pk=request.POST['choice'])
123 except (KeyError, Choice.DoesNotExist):
124 # Redisplay the question voting form.
125 return render(request, 'polls/detail.html', {
126 'question': question,
127 'error_message': "You didn't select a choice.",
128 })
129 else:
130 selected_choice.votes += 1
131 selected_choice.save()
132 # Always return an HttpResponseRedirect after successfully dealing
133 # with POST data. This prevents data from being posted twice if a
134 # user hits the Back button.
135 return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
136
137from django.contrib import admin
138
139from .models import Question
140
141admin.site.register(Question)
142polls/urls:
143
144from django.urls import path
145
146from . import views
147
148app_name = 'polls'
149urlpatterns = [
150 path('', views.IndexView.as_view(), name='index'),
151 path('<int:pk>/', views.DetailView.as_view(), name='detail'),
152 path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
153 path('<int:question_id>/vote/', views.vote, name='vote'),
154]
155
156<h1>{{ question.question_text }}</h1>
157<ul>
158{% for choice in question.choice_set.all %}
159 <li>{{ choice.choice_text }}</li>
160{% endfor %}
161</ul>
162
163<h1>{{ question.question_text }}</h1>
164
165{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %}
166
167<form action="{% url 'polls:vote' question.id %}" method="post">
168{% csrf_token %}
169{% for choice in question.choice_set.all %}
170 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
171 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br />
172{% endfor %}
173<input type="submit" value="Vote" />
174</form>
175
176<h1>{{ question.question_text }}</h1>
177
178<ul>
179{% for choice in question.choice_set.all %}
180 <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
181{% endfor %}
182</ul>
183
184<a href="{% url 'polls:detail' question.id %}">Vote again?</a>
185polls/templates/polls/index.html:
186
187{% if latest_question_list %}
188 <ul>
189 {% for question in latest_question_list %}
190 <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
191 {% endfor %}
192 </ul>
193{% else %}
194 <p>No polls are available.</p>
195{% endif %}
196
197"""
198Django settings for mysite3 project.
199
200Generated by 'django-admin startproject' using Django 2.0.
201
202For more information on this file, see
203https://docs.djangoproject.com/en/2.0/topics/settings/
204
205For the full list of settings and their values, see
206https://docs.djangoproject.com/en/2.0/ref/settings/
207"""
208
209import os
210
211# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
212BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
213
214
215# Quick-start development settings - unsuitable for production
216# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
217
218# SECURITY WARNING: keep the secret key used in production secret!
219SECRET_KEY = '*8a@se$l_8v%(-xyz=!!=jgvyjyn611zqw(dqroejvkk^o9%co'
220
221# SECURITY WARNING: don't run with debug turned on in production!
222DEBUG = True
223
224ALLOWED_HOSTS = []
225
226
227# Application definition
228
229INSTALLED_APPS = [
230 'django.contrib.admin',
231 'django.contrib.auth',
232 'django.contrib.contenttypes',
233 'django.contrib.sessions',
234 'django.contrib.messages',
235 'django.contrib.staticfiles',
236 'polls.apps.PollsConfig',
237]
238
239MIDDLEWARE = [
240 'django.middleware.security.SecurityMiddleware',
241 'django.contrib.sessions.middleware.SessionMiddleware',
242 'django.middleware.common.CommonMiddleware',
243 'django.middleware.csrf.CsrfViewMiddleware',
244 'django.contrib.auth.middleware.AuthenticationMiddleware',
245 'django.contrib.messages.middleware.MessageMiddleware',
246 'django.middleware.clickjacking.XFrameOptionsMiddleware',
247]
248
249ROOT_URLCONF = 'mysite3.urls'
250
251TEMPLATES = [
252 {
253 'BACKEND': 'django.template.backends.django.DjangoTemplates',
254 'DIRS': [],
255 'APP_DIRS': True,
256 'OPTIONS': {
257 'context_processors': [
258 'django.template.context_processors.debug',
259 'django.template.context_processors.request',
260 'django.contrib.auth.context_processors.auth',
261 'django.contrib.messages.context_processors.messages',
262 ],
263 },
264 },
265]
266
267WSGI_APPLICATION = 'mysite3.wsgi.application'
268
269
270# Database
271# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
272
273DATABASES = {
274 'default': {
275 'ENGINE': 'django.db.backends.sqlite3',
276 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
277 }
278}
279
280
281# Password validation
282# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
283
284AUTH_PASSWORD_VALIDATORS = [
285 {
286 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
287 },
288 {
289 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
290 },
291 {
292 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
293 },
294 {
295 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
296 },
297]
298
299
300# Internationalization
301# https://docs.djangoproject.com/en/2.0/topics/i18n/
302
303LANGUAGE_CODE = 'en-us'
304
305TIME_ZONE = 'UTC'
306
307USE_I18N = True
308
309USE_L10N = True
310
311USE_TZ = True
312
313
314# Static files (CSS, JavaScript, Images)
315# https://docs.djangoproject.com/en/2.0/howto/static-files/
316
317STATIC_URL = '/static/'