質問編集履歴
1
変更後のコードの追記
title
CHANGED
File without changes
|
body
CHANGED
@@ -100,4 +100,76 @@
|
|
100
100
|
|
101
101
|
staticファイルはしっかり参照できていると思います。
|
102
102
|
なにぶん、jQueryを習いたてなのでエラーの対処法がわかりません。
|
103
|
-
ご教授よろしくお願いします。
|
103
|
+
ご教授よろしくお願いします。
|
104
|
+
|
105
|
+
##追記
|
106
|
+
```views
|
107
|
+
def good_add(request):
|
108
|
+
post_pk = request.POST.get('post_pk')
|
109
|
+
post = Post.objects.get(pk=post_pk)
|
110
|
+
user = request.user
|
111
|
+
if Good.objects.filter(user=user, target=post).exists():
|
112
|
+
good = Good.objects.get(user=user, target=post)
|
113
|
+
good.delete()
|
114
|
+
else:
|
115
|
+
Good.objects.create(target=post, user=user)
|
116
|
+
if post.is_good is None:
|
117
|
+
post.is_good = False
|
118
|
+
post.save()
|
119
|
+
good_counts = Good.objects.filter(target=post).count()
|
120
|
+
d = {
|
121
|
+
'good_counts': good_counts,
|
122
|
+
}
|
123
|
+
return JsonResponse(d)
|
124
|
+
```
|
125
|
+
```html
|
126
|
+
<h2>高評価</h2>
|
127
|
+
<div id="good_count">
|
128
|
+
<p>{{ object.good_set.count }}</p>
|
129
|
+
</div>
|
130
|
+
<br>
|
131
|
+
<h2>Goodの追加</h2>
|
132
|
+
<form id="good_add" action="{% url 'note:good_add' %}" method="POST">
|
133
|
+
<input type="hidden" id="post_id_for_good" value={{ object.pk }}>
|
134
|
+
<button type="submit">送信</button>
|
135
|
+
{% csrf_token %}
|
136
|
+
</form>
|
137
|
+
|
138
|
+
<script src="{% static 'js/push_good.js' %}"></script>
|
139
|
+
```
|
140
|
+
```push_good
|
141
|
+
const getCookie = name =>{
|
142
|
+
if (document.cookie && document.cookie !== '') {
|
143
|
+
for (const cookie of document.cookie.split(';')){
|
144
|
+
const [key, value] = cookie.trim().split('=');
|
145
|
+
if(key === name) {
|
146
|
+
return decodeURIComponent(value);
|
147
|
+
}
|
148
|
+
}
|
149
|
+
}
|
150
|
+
};
|
151
|
+
const csrftoken = getCookie('csrftoken');
|
152
|
+
|
153
|
+
document.getElementById('good_add').addEventListener('submit', e => {
|
154
|
+
e.preventDefault();
|
155
|
+
|
156
|
+
const url = document.getElementById('good_add').action;
|
157
|
+
const post_id = encodeURIComponent(document.getElementById('post_id_for_good').value);
|
158
|
+
fetch(url, {
|
159
|
+
method: 'POST',
|
160
|
+
body: `post_pk=${post_id}`,
|
161
|
+
headers: {
|
162
|
+
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
|
163
|
+
'X-CSRFToken': csrftoken,
|
164
|
+
},
|
165
|
+
}).then(response => {
|
166
|
+
return response.json();
|
167
|
+
}).then(response => {
|
168
|
+
$('#good_count').empty();
|
169
|
+
const p = $('<p>', {text: response.good_counts});
|
170
|
+
$('#good_count').append(p);
|
171
|
+
}).catch(error => {
|
172
|
+
console.log(error);
|
173
|
+
});
|
174
|
+
});
|
175
|
+
```
|