練習用のニュースフィードWebサイトを作成してDjangoを学んでいます。ニュースフィードページで、[いいね]ボタンの投稿にいいねの数を表示します。以下の2つのコードブロックを参照してください-
- views.py - Here I have put all my posts in all_posts and then has looped through the posts to get the count of total likes on this post from a Likes table in the model (If there is a better way please suggest) into the likes dictionary.
all_posts = NewsFeed.objects.all().order_by('time').reverse()
likes = {}
for post in all_posts:
likes_count = Likes.objects.filter(newsfeed = post).count()
likes[post.id] = likes_count
form = StatusForm()
context = {
'name': name,
'all_posts': all_posts,
'statusForm': form,
'likes': likes,
}
- index.html - Here I want to display all the posts and a like button for each post which would also display the number of likes on the post. When I am manually trying to access the likes count {{ likes.4 }} it is displaying correct count for the fourth status Like(1) but when I try to access it like {{ likes.post_id }} it displays nothing Like(). Please help me out as I am new to this and also provide with the suggestions to do the same in a better way if there's any.
{% for post in all_posts %}
<div class="newsfeed-div">
<h3>{{ post.title }}</h3>
<p>{{ post.content }}</p>
<pre>{{ post.user.name }}</pre>
<pre>{{ post.time }}</pre>
{% with post_id=post.id %}
<a href="{% url 'newsfeed:likeStatus' post.id %}"><button>Like({{ likes.post_id }})</button></a>
<a href="#"><button>Comment(0)</button></a>
{% endwith %}
</div><hr/>
{% endfor %}
次のようなものを使用する場合:
{{likes.4}}4番目のニュースフィードでいいね!
{{likes.post_id}}動かない?
私を助けてください、そして、より良い方法で同じことを達成するためのあなたの提案も提供してください。
回答 1 件
関連記事
- jest ReferenceError:初期化前に ''にアクセスできません
- AzureB2Cで保護されたNETCoreAPIにアクセスするReactアプリでアクセストークンを取得できません
- Pythonはリストにアクセスできません
- CORS構成でS3リソースにアクセスできません
- ReactNativeはコンポーネントの小道具にアクセスできません
- Django ORMエラー:主キーにNULLを挿入できません
- ルーターを使用して、あるコンポーネントから別のReactJSに渡されたデータにアクセスする方法
- SynologyサーバーをRaspberryPiにマウントできませんが、ファイルブラウザーでアクセスできます(マウントエラー(2):そのようなファイルまたはディレクトリはありません)
- 変換せずにインラインスクリプト内でPUGに渡されたオブジェクトにアクセスする方法
- Django ModelForm:テンプレートに渡されない値を定義する
関連した質問
- オブジェクト==なしの場合にアイテムを非表示にするDjango
- Djangoのテンプレートに渡されるクエリセットに関連するクエリセットオブジェクトを取得するにはどうすればよいですか?
- モデル選択からフィールドを表示する方法
- 「友人」には属性「META」エラーはありません不明な理由:ジャンゴ
- テンプレートのジャンゴブールフィールド
- Django:liなしのformsetエラー/ *
- Django:Taggitタグをループしてアルファベット順にリストし、同時にテンプレートでそれらを分離する方法
- UnicodeEncodeErrorを修正するためのDjangoサードパーティライブラリテンプレートタグのオーバーライド
- テンプレートの条件ロジックにテンプレートタグの戻り値を使用する
Djangoテンプレートは、変数キーによるインデックス作成をサポートしていません。同様の質問については、テンプレートのディクショナリ値にアクセスできない(オブジェクトpkがdictキーです)をご覧ください。
そうは言っても、あなたの問題は
ザ・
_set
接尾辞は、RelatedManager
のデフォルト名の規則です これは、1対多の関係ですべての子レコードを返します(すべてのlikes
特定のpost
に属する この例では)および.count
行数を返します。