質問編集履歴

1

変更後のコードの追記

2020/03/25 17:01

投稿

yukoishii
yukoishii

スコア16

test CHANGED
File without changes
test CHANGED
@@ -203,3 +203,147 @@
203
203
  なにぶん、jQueryを習いたてなのでエラーの対処法がわかりません。
204
204
 
205
205
  ご教授よろしくお願いします。
206
+
207
+
208
+
209
+ ##追記
210
+
211
+ ```views
212
+
213
+ def good_add(request):
214
+
215
+ post_pk = request.POST.get('post_pk')
216
+
217
+ post = Post.objects.get(pk=post_pk)
218
+
219
+ user = request.user
220
+
221
+ if Good.objects.filter(user=user, target=post).exists():
222
+
223
+ good = Good.objects.get(user=user, target=post)
224
+
225
+ good.delete()
226
+
227
+ else:
228
+
229
+ Good.objects.create(target=post, user=user)
230
+
231
+ if post.is_good is None:
232
+
233
+ post.is_good = False
234
+
235
+ post.save()
236
+
237
+ good_counts = Good.objects.filter(target=post).count()
238
+
239
+ d = {
240
+
241
+ 'good_counts': good_counts,
242
+
243
+ }
244
+
245
+ return JsonResponse(d)
246
+
247
+ ```
248
+
249
+ ```html
250
+
251
+ <h2>高評価</h2>
252
+
253
+ <div id="good_count">
254
+
255
+ <p>{{ object.good_set.count }}</p>
256
+
257
+ </div>
258
+
259
+ <br>
260
+
261
+ <h2>Goodの追加</h2>
262
+
263
+ <form id="good_add" action="{% url 'note:good_add' %}" method="POST">
264
+
265
+ <input type="hidden" id="post_id_for_good" value={{ object.pk }}>
266
+
267
+ <button type="submit">送信</button>
268
+
269
+ {% csrf_token %}
270
+
271
+ </form>
272
+
273
+
274
+
275
+ <script src="{% static 'js/push_good.js' %}"></script>
276
+
277
+ ```
278
+
279
+ ```push_good
280
+
281
+ const getCookie = name =>{
282
+
283
+ if (document.cookie && document.cookie !== '') {
284
+
285
+ for (const cookie of document.cookie.split(';')){
286
+
287
+ const [key, value] = cookie.trim().split('=');
288
+
289
+ if(key === name) {
290
+
291
+ return decodeURIComponent(value);
292
+
293
+ }
294
+
295
+ }
296
+
297
+ }
298
+
299
+ };
300
+
301
+ const csrftoken = getCookie('csrftoken');
302
+
303
+
304
+
305
+ document.getElementById('good_add').addEventListener('submit', e => {
306
+
307
+ e.preventDefault();
308
+
309
+
310
+
311
+ const url = document.getElementById('good_add').action;
312
+
313
+ const post_id = encodeURIComponent(document.getElementById('post_id_for_good').value);
314
+
315
+ fetch(url, {
316
+
317
+ method: 'POST',
318
+
319
+ body: `post_pk=${post_id}`,
320
+
321
+ headers: {
322
+
323
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
324
+
325
+ 'X-CSRFToken': csrftoken,
326
+
327
+ },
328
+
329
+ }).then(response => {
330
+
331
+ return response.json();
332
+
333
+ }).then(response => {
334
+
335
+ $('#good_count').empty();
336
+
337
+ const p = $('<p>', {text: response.good_counts});
338
+
339
+ $('#good_count').append(p);
340
+
341
+ }).catch(error => {
342
+
343
+ console.log(error);
344
+
345
+ });
346
+
347
+ });
348
+
349
+ ```