質問編集履歴

1

追記

2021/04/15 03:20

投稿

Mario_11
Mario_11

スコア95

test CHANGED
@@ -1 +1 @@
1
- Django AjaxでIikeボタン作成
1
+ javascript preventDefault使い方
test CHANGED
@@ -1,250 +1,58 @@
1
1
  Django AjaxでIikeボタンの作成をしています。
2
2
 
3
- ー参考サイトー
4
-
5
- [https://github.com/hellopyplane/Social-Network](https://github.com/hellopyplane/Social-Network)
6
-
7
- 上記のコードを参考にしてLikeボタン作成できたのですが、Likeを押す際にページが読み込まれてしまいます。
3
+ Likeを押す際にページを読み込みたくないのです、が読み込まれてしまいます。
8
-
9
- バージョンなどは全て最新にしましたが、上手くいきませんでした。
10
4
 
11
5
 
12
6
 
13
- どうればページが読み込まれずにLikeを押せますか?
7
+ `preventDefault`の指定箇所をいろいろ変更してみたのですが読み込まれてしいま
14
8
 
9
+ そもそも書き方が違うのでしょうか?
15
10
 
16
-
17
-
18
-
19
-
20
-
21
- ```python
22
-
23
- models.py
24
-
25
-
26
-
27
- class Item(models.Model):
28
-
29
- post_user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
30
-
31
- title = models.CharField(verbose_name='タイトル',max_length=200,)
32
-
33
- memo = models.TextField(verbose_name='備考',max_length=300,blank=True,null=True,)
34
-
35
- created_at = models.DateTimeField(verbose_name='登録日',auto_now_add=True)
36
-
37
- liked = models.ManyToManyField('User', blank=True, related_name='likes')
38
-
39
-
40
-
41
- # 管理サイト上の表示設定
42
-
43
- def __str__(self):
44
-
45
- return self.title
46
-
47
-
48
-
49
- class Meta:
50
-
51
- verbose_name = 'アイテム'
52
-
53
- verbose_name_plural = 'アイテム'
54
-
55
-
56
-
57
- def num_likes(self):
58
-
59
- return self.liked.all().count()
60
-
61
- ```
62
-
63
-
64
-
65
- ```python
66
-
67
- #Likeボタン実装
68
-
69
- @login_required
70
-
71
- def like_unlike_post(request):
72
-
73
- user = request.user
74
-
75
- if request.method == 'POST':
76
-
77
- post_id = request.POST.get('post_id')
78
-
79
- post_obj = Item.objects.get(id=post_id)
80
-
81
- profile = User.objects.get(user_name=user)
82
-
83
-
84
-
85
- if profile in post_obj.liked.all():
86
-
87
- post_obj.liked.remove(profile)
88
-
89
- else:
90
-
91
- post_obj.liked.add(profile)
92
-
93
-
94
-
95
- like, created = Like.objects.get_or_create(user=profile, post_id=post_id)
96
-
97
-
98
-
99
- if not created:
100
-
101
- if like.value=='Like':
11
+ 他に必要なものがあれば追記いたします。よろしくお願いいたします。
102
-
103
- like.value='Unlike'
104
-
105
- else:
106
-
107
- like.value='Like'
108
-
109
- else:
110
-
111
- like.value='Like'
112
-
113
-
114
-
115
- post_obj.save()
116
-
117
- like.save()
118
-
119
-
120
-
121
- #data = {'value': like.value,'likes': post_obj.liked.all().count()}
122
-
123
- #return JsonResponse(data, safe=False)
124
-
125
- return redirect('app:top')
126
-
127
- ```
128
-
129
-
130
-
131
- ```python
132
-
133
- urls.py
134
-
135
- path('', ItemFilterView.as_view(), name='top'),
136
-
137
- path('liked/', like_unlike_post, name='like-post-view'),
138
-
139
-
140
-
141
- ```
142
12
 
143
13
 
144
14
 
145
15
  ```html
146
16
 
147
- <div class="right floated">
17
+ <form action="{% url 'app:like-post-view' %}" method="POST" class='like-form' id='{{item.id}}'>
148
18
 
149
- <form action="{% url 'app:like-post-view' %}" method="POST" class='like-form' id='{{item.id}}'>
19
+ {% csrf_token %}
150
20
 
151
- {% csrf_token %}
21
+ <input type="hidden" name="post_id" value={{item.id}}>
152
22
 
153
- <input type="hidden" name="post_id" value={{item.id}}>
23
+ <div class="LikesIcon">
154
24
 
155
-
25
+ {% if user not in item.liked.all %}
156
26
 
157
- <button type="submit" class="ui button like-btn{{item.id}}">
27
+ <i class="far fa-heart LikesIcon-fa-heart"></i><div class="like-count{{item.id}}"></div>
158
28
 
159
- {% if profile not in item.liked.all %}
29
+ {% else %}
160
30
 
161
- Like<div class="like-count{{item.id}}">{{item.num_likes}}</div>
31
+ <i class="fas fa-heart LikesIcon-fa-heart" style="color:red;"></i><div class="like-count{{item.id}}"></div>
162
32
 
163
- {% else %}
33
+ {% endif %}
164
34
 
165
- Unlike<div class="like-count{{item.id}}">{{item.num_likes}}</div>
35
+ </div>
166
36
 
167
- {% endif %}
37
+ </form>
168
38
 
169
- </button>
39
+ ```
170
40
 
171
- </form>
41
+ ```javascript
172
42
 
173
- </div>
43
+ <script>
44
+
45
+ $('.like-form').click(function() {
46
+
47
+ $('form').submit();
48
+
49
+ });
174
50
 
175
51
 
176
52
 
177
- {% block extrajs %}
53
+ $('.like-form').submit(function(e){
178
54
 
179
- <script>
180
-
181
- function getCookie(name) {
182
-
183
- var cookieValue = null;
184
-
185
- if (document.cookie && document.cookie !== '') {
186
-
187
- var cookies = document.cookie.split(';');
188
-
189
- for (var i = 0; i < cookies.length; i++) {
190
-
191
- var cookie = jQuery.trim(cookies[i]);
192
-
193
- // Does this cookie string begin with the name we want?
194
-
195
- if (cookie.substring(0, name.length + 1) === (name + '=')) {
196
-
197
- cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
198
-
199
- break;
200
-
201
- }
202
-
203
- }
204
-
205
- }
206
-
207
- return cookieValue;
208
-
209
- }
210
-
211
-
212
-
213
- var csrftoken = getCookie('csrftoken');
214
-
215
-
216
-
217
- function csrfSafeMethod(method) {
218
-
219
- // these HTTP methods do not require CSRF protection
220
-
221
- return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
222
-
223
- }
224
-
225
-
226
-
227
- $.ajaxSetup({
228
-
229
- beforeSend: function (xhr, settings) {
230
-
231
- if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
232
-
233
- xhr.setRequestHeader("X-CSRFToken", csrftoken);
234
-
235
- }
236
-
237
- }
238
-
239
- });
240
-
241
-
242
-
243
- $('#like-form').on('submit', e => {
244
-
245
- // デフォルトのイベントをキャンセルし、ページ遷移しないように!
246
-
247
- e.preventDefault();
55
+ e.preventDefault()
248
56
 
249
57
 
250
58
 
@@ -252,11 +60,9 @@
252
60
 
253
61
 
254
62
 
255
- const likeText = $(`.like-btn${post_id}`).text()
63
+ const hasLike = $(`.LikesIcon${post_id}`).find('i').hasClass('like')
256
64
 
257
- const trim = $.trim(likeText)
65
+
258
-
259
-
260
66
 
261
67
  const url = $(this).attr('action')
262
68
 
@@ -286,15 +92,15 @@
286
92
 
287
93
  success: function(response) {
288
94
 
289
- if(trim === 'Unlike') {
95
+ if(hasLike) {
290
96
 
291
- $(`.like-btn${post_id}`).text('Like')
97
+ $(`.like-btn${post_id}`).html('<i class="far fa-heart LikesIcon-fa-heart"></i>')
292
98
 
293
99
  res = trimCount - 1
294
100
 
295
101
  } else {
296
102
 
297
- $(`.like-btn${post_id}`).text('Unlike')
103
+ $(`.like-btn${post_id}`).html('<i class="fas fa-heart LikesIcon-fa-heart"></i>')
298
104
 
299
105
  res = trimCount + 1
300
106
 
@@ -314,20 +120,44 @@
314
120
 
315
121
  })
316
122
 
123
+ })
317
124
 
125
+ // Likeボタンクリック
126
+
127
+ $('.LikesIcon').on('click', function() {
128
+
129
+ let $btn = $(this);
130
+
131
+ // Likeボタンがonクラス持っていたら
132
+
133
+ if ($btn.hasClass('on')) {
134
+
135
+
136
+
137
+ $btn.removeClass('on');
138
+
139
+
140
+
141
+ // 白抜きアイコンに戻す
142
+
143
+ $btn.children("i").attr('class', 'far fa-heart LikesIcon-fa-heart');
144
+
145
+
146
+
147
+ } else {
148
+
149
+ $btn.addClass('on');
150
+
151
+ $btn.children("i").attr('class', 'fas fa-heart LikesIcon-fa-heart heart');
152
+
153
+
154
+
155
+ }
318
156
 
319
157
  })
320
158
 
159
+
160
+
321
161
  </script>
322
162
 
323
- {% endblock %}
324
-
325
-
326
-
327
163
  ```
328
-
329
-
330
-
331
- Ajaxが間違っていると思い[このサイト](https://blog.narito.ninja/detail/88/)を見ながらやってもページがローディングされます。
332
-
333
- よろしくお願いします。