python=3.7.0
django=(2, 0, 2, 'final', 0)
の環境で開発しています。
Djangoチュートリアルで学んだ投票アプリに改造を加えコメント投稿機能を追加しております。
Djangoチュートリアル。
https://docs.djangoproject.com/ja/2.1/intro/tutorial01/
前提・実現したいこと
質問ごとに選択肢を設けコメントともに(空欄可能)投票させるアプリを作成していますが、選択肢にフィルターをかけられずに悩んでおります。
ベルマーレMVPへの質問の選択肢は2つ目の画像の選択しだけなのだが実際には他の質問への選択肢や------
という選択肢が表出されてしまう。
前提条件としてコードは
models.py
python
1class Choice(models.Model): 2 question = models.ForeignKey(Question, on_delete=models.CASCADE) 3 choice_text = models.CharField(max_length=200) 4 votes = models.IntegerField(default=0) 5 6 def __str__(self): 7 return self.choice_text 8 9 10class Choice_Comment(models.Model): 11 choice = models.ForeignKey(Choice, on_delete=models.CASCADE) 12 choice_comment_text = models.TextField('コメント', blank=True, null=True) 13
forms.py
python
1class ChoiceCommentForm(forms.ModelForm): 2 choice =forms.ModelChoiceField( 3 queryset=Choice.objects.all(), 4 widget=forms.RadioSelect, 5 ) 6 7 class Meta: 8 model = Choice_Comment 9 fields ="__all__"
views.py
python
1 2class DetailView(ModelFormMixin, generic.DetailView): 3 model = Question 4 template_name = 'polls/detail.html' 5 form_class = ChoiceCommentForm 6 def get_queryset(self): 7 return Question.objects.filter(pub_date__lte=timezone.now()) 8 9 10def vote(request, question_id): 11 question = get_object_or_404(Question, pk=question_id) 12 form = ChoiceCommentForm(request.POST or None) 13 try: 14 selected_choice= question.choice_set.get(pk=request.POST['choice']) 15 except (KeyError, Choice.DoesNotExist): 16 return render(request, 'polls/detail.html', { 17 'question': question, 18 'error_message': "投票内容を選んでください", 19 }) 20 else: 21 selected_choice.votes += 1 22 selected_choice.save() 23 form.save() 24 context ={ 25 'comment_ichiran':selected_choice, 26 } 27 return HttpResponseRedirect(reverse('polls:results', args=(question.id,)), context)
urls.py
python
1from django.urls import path 2 3from . import views 4 5app_name = 'polls' 6urlpatterns = [ 7 path('', views.IndexView.as_view(), name='index'), 8 path('<int:pk>/', views.DetailView.as_view(), name='detail'), 9 path('<int:pk>/results/', views.ResultsView.as_view(), name='results'), 10 path('<int:question_id>/vote/', views.vote, name='vote'), 11 path('<int:post_pk>/comment/', views.CommentView.as_view(), name='comment'), 12 path('<int:pk>/comment_list/', views.commentlist, name='comment_list'), 13] 14
detail.html
html
1<h1>{{ question.question_text }}</h1> 2 3{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 4 5<form action="{% url 'polls:vote' question.id %}" method="post"> 6{% csrf_token %} 7 8{{ form.as_p }} 9 10<input type="submit" value="投票"> 11 12</form> 13
forms.pyの
queryset=Choice.objects.all(),
filterをうまくかければその質問に対する質問だけを表示できると思いいろいろ試してました。
試したこと
forms.py
python
1class ChoiceCommentForm(forms.ModelForm): 2 choice_text = Choice.objects.all() 3 choice =forms.ModelChoiceField( 4 #queryset=Choice.objects.all(), 5 queryset = Choice.objects.filter(choice_text=choice_text).all().order_by('pk'), 6 widget=forms.RadioSelect, 7 ) 8 9 class Meta: 10 model = Choice_Comment 11 fields ="__all__" 12
エラーメッセージ
error
1Error during template rendering 2In template C:\Users\Desktop\mysite\polls\templates\polls\detail.html, error at line 13 3 4The QuerySet value for an exact lookup must be limited to one result using slicing. 53 {% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 64 75 <form action="{% url 'polls:vote' question.id %}" method="post"> 86 {% csrf_token %} 97 {% for choice in question.choice_set.all %} 108 <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> 119 <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label><br> 1210 {% endfor %} 1311 1412 1513 {{ form.as_p }} 1614 1715 <input type="submit" value="投票"> 1816 1917 </form> 2018
試したこと2
forms.py
コード
python
1class ChoiceCommentForm(forms.ModelForm): 2 choice_text = get_object_or_404(Question, pk=question_id) 3 choice =forms.ModelChoiceField( 4 #queryset=Choice.objects.all(), 5 queryset = Choice.objects.filter(choice_text=choice_text), 6 widget=forms.RadioSelect, 7 ) 8 9 class Meta: 10 model = Choice_Comment 11 fields ="__all__" 12
エラーメッセージ
error
1 class ChoiceCommentForm(forms.ModelForm): 2 File "C:\Users\Desktop\mysite\polls\forms.py", line 20, in ChoiceC 3ommentForm 4 choice_text = get_object_or_404(Question, pk=question_id) 5NameError: name 'question_id' is not defined
試したこと3
forms.py
python
1class ChoiceCommentForm(forms.ModelForm): 2 #choice_text = models.ForeignKey(Question, on_delete=models.CASCADE) 3 choice =forms.ModelChoiceField( 4 #queryset=Choice.objects.all(), 5 queryset = Choice.objects.filter(pk=1), 6 widget=forms.RadioSelect, 7 ) 8 9 class Meta: 10 model = Choice_Comment 11 fields ="__all__" 12
エラーメッセージは出ずにpk=1の選択肢だけが出てきました。
試したこと4
forms.py
python
1class ChoiceCommentForm(forms.ModelForm): 2 choice_text = models.ForeignKey(Question, on_delete=models.CASCADE) 3 choice =forms.ModelChoiceField( 4 #queryset=Choice.objects.all(), 5 queryset = Choice.objects.filter(choice_text=choice_text), 6 widget=forms.RadioSelect, 7 ) 8 9 class Meta: 10 model = Choice_Comment 11 fields ="__all__"
error
1 "Choices are: %s" % (name, ", ".join(available))) 2django.core.exceptions.FieldError: Cannot resolve keyword 'choice_text' into fie 3ld. Choices are: choice, comment, id, pub_date, question_text
quesrysetの手法を理解しきれてないいないためドキュメントで勉強中です。
https://docs.djangoproject.com/ja/2.1/topics/db/queries/
おそらく
urls.py
1path('<int:pk>/', views.DetailView.as_view(), name='detail'),
のpkを読み取れれば解決すると思うのですが・・・。
アドバイスをお願いいたします。
回答1件
あなたの回答
tips
プレビュー