0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

一対多モデルでのdjangoデンプレートが表示されない時の確認した方がいい箇所

Last updated at Posted at 2020-06-28

一対多モデルを制作してhtmlに出力する時につまったところを解説。

今回はモデルに値を渡すことができたけど出力ができない時、確認した方がいいところを記載します。

<div>
{% for comment post.comments.all %}
{{ comment.user }}
{{ comment.text }}
{% endfor %}
</div>

今回はこのようなhtmlを出力して見たいと思います。

確認するべき点は三箇所
1.templateに出力するオブジェクトの書き方
2.related_nameをちゃんと定義しているか
3.viewsの設定

①templateに出力するオブジェクトの書き方

<div>
{% for comment post.comments.all %}
{{ comment.user }}
{{ comment.text }}
{% endfor %}
</div>

post.comments.all

コイツの具体的な書き方がわからなかったので、コイツの説明

post は変数でviewで渡した時の返り値

views.py
def Post(request):
    form = PostChatMessage()
    if request.method == 'POST':
       form = PostChatMessage(request.POST, request.FILES)
       if form.is_valid():
           post = form.save(commit=False)
           post.nickname = request.user
           post.save()
           return redirect('chat')
       else:
           form = PostChatMessage()
           return render(request, 'ChatSend.html', コイツ{'error': 'Please type message'})
    return render(request, 'ChatSend.html', コイツ{'form':form})

commnets はmodels.pyで定義したrelated_name

model.py

------
def Comment(models.Model):
    post = models.ForeignKey(ChatMessage, on_delete=models.CASCADE, related_name='comments')
--------

です。
お間違えのないように

②related_nameをちゃんと定義しているか

related_nameが定義されていなくても
model名_setで同等の使い方ができます。
又related_nameが定義されていても子model名とおんなじ名前だと動かないみたいです。

③viewsの設定

自分はここで詰まりました。

views.py
def ShowComments(request, pk):
    post = get_object_or_404(ChatMessage, pk=pk)
    return render(request, 'Comments.html', {'post':post}) 
views.py
def ShowComments(request):
    post = Comment.object.all()
    return render(request, 'Comments.html', {'post':post}) 

下でも表示はされますが、一対多の関連付けが表示されないので子モデルが全て表示されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?