質問編集履歴
1
試したことの追加
title
CHANGED
File without changes
|
body
CHANGED
@@ -175,6 +175,7 @@
|
|
175
175
|
|
176
176
|
|
177
177
|
### 発生している問題・エラーメッセージ
|
178
|
+
非ログインユーザーが記事詳細ページにアクセスすると、`AnonymousUser' object is not iterable`エラーが発生します。
|
178
179
|
```
|
179
180
|
TypeError at /article_detail/10
|
180
181
|
'AnonymousUser' object is not iterable
|
@@ -189,5 +190,37 @@
|
|
189
190
|
Python Version: 3.7.6
|
190
191
|
```
|
191
192
|
### 試したこと
|
193
|
+
ログイン済ユーザーでアクセスした場合は、エラーが起きず正常に作動しました。また、`views.py`の`ArticleDetailView`クラスの`get_context_data`メソッド内で、`self.request.user`が`AnonymousUser`の場合に`is_user_liked_for_article`を`False`に設定しましたが、エラーが解決しませんでした。
|
192
194
|
|
193
|
-
ログイン
|
195
|
+
どのように修正すればエラーが解決し、非ログインユーザーが記事詳細ページにアクセスできるようになりますか?
|
196
|
+
```views.py
|
197
|
+
class ArticleDetailView(generic.DetailView):
|
198
|
+
model = Article
|
199
|
+
template_name = 'article_detail.html'
|
200
|
+
|
201
|
+
def get(self, request, *args, **kwargs): #閲覧数のカウント処理
|
202
|
+
self.object = self.get_object()
|
203
|
+
self.object.view_count += 1
|
204
|
+
self.object.save()
|
205
|
+
context = self.get_context_data(object=self.object)
|
206
|
+
return self.render_to_response(context)
|
207
|
+
|
208
|
+
def get_context_data(self, **kwargs): #ユーザが既にイイねしているかどうかの判断
|
209
|
+
context = super().get_context_data(**kwargs)
|
210
|
+
|
211
|
+
like_for_article_count = self.object.likeforarticle_set.count()
|
212
|
+
#記事に対するイイね数
|
213
|
+
context['like_for_article_count'] = like_for_article_count
|
214
|
+
|
215
|
+
#非ログインユーザーの場合
|
216
|
+
if self.request.user.id is None:
|
217
|
+
context['is_user_liked_for_article'] = False
|
218
|
+
|
219
|
+
#ログインユーザがイイねしているかどうか
|
220
|
+
if self.object.likeforarticle_set.filter(user=self.request.user).exists():
|
221
|
+
context['is_user_liked_for_article'] = True
|
222
|
+
else:
|
223
|
+
context['is_user_liked_for_article'] = False
|
224
|
+
|
225
|
+
return context
|
226
|
+
```
|