python=3.7.0
django=(2, 0, 2, 'final', 0)
の環境で開発しています。
djangoチュートリアルを参考に簡単な投票アプリを作成しました。
djangoチュートリアル
https://docs.djangoproject.com/ja/2.1/intro/tutorial01/
作成したもののコード
https://github.com/sr2460/polls
これをさらに改造し、投票ページにコメント欄を設けこのコメントが投票結果のページに反映されるようにしようとしています。
まずmodels.pyを改造する必要があると思ったので
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0)
を
class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) **comment = models.TextField()**←追加
comment = models.TextField()でText.Field()を追加しました。
するとコマンドプロンプトにエラー
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: polls_choice.comment
画面にもエラーが出ました。
modelsの変更なのでmigrationをすれば良いかと思いコマンドを入力しましたが、
You are trying to add a non-nullable field 'comment' to choice without a default ; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py Select an option:
と文章が出まして、以前これをむりやりmigrateしたところなにかおかしくなってしまったのでとりあえず保留し、さらにコードを修正することにしました。
views.pyにcomment = models.TextField()に対応するものがないのでコードを追加
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): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "投票内容を選んでください", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,)))
choice_comment = question.comment.get(pk=request.POST['choice'])を定義し、modelsで作成したcomment = models.TextField()を呼び出し、
さらに
choice_comment.save()と記載し、コメントを保存させようとしました。
しかし再び同様のエラーが出てしまいました。
まずcomment = models.TextField()を反映させるためにどうmigrateすればよいのか?
さらにviewsにcommentを反映させるために(特にこの部分だと思うのですがquestion.comment.get)
をどう改造すればよいのか?
を調べているのですがどうしてもわからないので質問させていただきました。
ちなみに投票結果のページに対応するhtmlは
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_text }}</label><br> {% endfor %} <input type="submit" value="投票"> </form>
urlは
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
となっています。
何卒よろしくお願いいたします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。