ListViewとCreateを1つのページに表示するようにこのようなコードを書きました。
python
1#views.py 2 3class PostandBoard(generic.CreateView): 4 model = Post 5 form_class = PostForm 6 template_name = 'board/board.html' 7 success_url = reverse_lazy('board:index') 8 9 10class IndexView(generic.ListView): 11 model = Post 12 13 14 15class FormAndListView(PostandBoard, IndexView,): 16 def get(self, request, *args, **kwargs): 17 formView = PostandBoard.get(self, request, *args, **kwargs) 18 listView = IndexView.get(self, request, *args, **kwargs) 19 formData = formView.context_data['form'] 20 listData = listView.context_data['object_list'] 21 context = {'form' : formData, 'post_list' : listData} 22 return render(request, 'board/test.html', context)
html
1#test.html 2 3<form action="" method="POST"> 4{{ form.as_p }} 5<button type="submit">送信</button> 6{% csrf_token %} 7</form> 8 9 10{% for post in post_list %} 11 12<p>{{ post.name }}</p> 13<p>{{ post.text | linebreaksbr }}</p> 14<p>{{ post.date }}</p> 15 16{% endfor %} 17 18
これでCreateViewとListViewを1つのページで表示できたのですが、
formData = formView.context_data['form'] listData = listView.context_data['object_list']
の['form']と['object_list']の役割がよくわかりません。
context_dataはformViewやListViewのデータを渡しているのでしょうが、'form'と'object_list'に関してはテンプレートなどでも使っていないのですが、消すと送信ボタン以外はすべての表示が消えてしまいます。
なので現状このまま書いてはいるのですが、なぜこれを消すと表示が消えてしまうのか理解はし切れていないのです。
もしよければご教示いただけると幸いです。

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/01/23 07:23 編集