teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

1

追加ファイルとファイル構造を記載しました。

2021/03/05 08:46

投稿

mAsuo_pro
mAsuo_pro

スコア0

title CHANGED
@@ -1,1 +1,1 @@
1
- [Django] jsファイルが反応しない
1
+ djangoでjsファイルが反応しない
body CHANGED
@@ -4,8 +4,26 @@
4
4
  デバッグを見るとjsファイルは読み込まれているようですが、反応していません。
5
5
  解決していただけると助かります。
6
6
 
7
+
7
8
  エラーメッセージはありませんが、デバッグをfluseにすると500エラーが発生します。
8
9
 
10
+ **試したこと**
11
+ ・スーパーリロード
12
+ ・django-static-md5urlを使う
13
+ ・キャッシュバスティングの設定(500エラーの発生)
14
+
15
+ **ファイル構造**
16
+ cissapp/
17
+ ├ciss
18
+ | └views.py
19
+ ├static
20
+ | └js
21
+ | └vote.js
22
+ ├template
23
+ | └detail.html
24
+
25
+
26
+
9
27
  views.py
10
28
  ```views.py
11
29
  class TopicDetailView(FormView):
@@ -42,42 +60,17 @@
42
60
  ```
43
61
  models.py
44
62
  ```models.py
45
- from django.db import models
46
- from django.utils import timezone
47
- from django.contrib.auth import get_user_model
48
-
49
-
50
63
  class Data(models.Model):
51
64
  category = models.CharField("科目種別", blank=True, max_length=100)
52
65
  no = models.CharField("授業番号", blank=True, max_length=10)
53
66
  semester = models.CharField("学期", blank=True, max_length=5)
54
67
  day = models.CharField("曜日", blank=True, max_length=1)
55
68
  name = models.CharField("科目", blank=True, max_length=20)
56
- period = models.CharField("時限", blank=True, max_length=2)
57
- teacher = models.CharField("担当教員", blank=True, max_length=30)
58
- credit = models.CharField("単位", blank=True, max_length=1)
59
69
 
60
- class Meta:
61
- verbose_name = '授業'
62
- verbose_name_plural = '授業一覧'
63
70
 
64
71
  def __str__(self):
65
72
  return(self.name)
66
73
 
67
-
68
- # Create your models here.
69
- class TopicManager(models.Manager):
70
- # Topic操作に関する処理を追加
71
- pass
72
-
73
- class CommentManager(models.Manager):
74
- # Comment操作に関する処理を追加
75
- pass
76
-
77
- class CategoryManager(models.Manager):
78
- # Category操作に関する処理を追加
79
- pass
80
-
81
74
  class Topic(models.Model):
82
75
  id = models.BigAutoField(
83
76
  primary_key=True,
@@ -113,16 +106,8 @@
113
106
  pub_flg = models.BooleanField(
114
107
  default=True,
115
108
  )
116
- modified = models.DateTimeField(
117
- auto_now=True,
118
- )
119
- objects = TopicManager()
120
109
 
121
- class Meta:
122
- verbose_name = '投稿'
123
- verbose_name_plural = '投稿一覧'
124
110
 
125
-
126
111
  def __str__(self):
127
112
  return '{}-{}'.format(self.data.id, self.no)
128
113
 
@@ -189,27 +174,11 @@
189
174
  ```
190
175
  setting.py
191
176
  ```ここに言語を入力
192
- import os
193
- from pathlib import Path
194
177
 
195
- # Build paths inside the project like this: BASE_DIR / 'subdir'.
196
- BASE_DIR = Path(__file__).resolve().parent.parent
197
-
198
-
199
- # Quick-start development settings - unsuitable for production
200
- # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
201
-
202
- # SECURITY WARNING: keep the secret key used in production secret!
203
- SECRET_KEY = 'hiv6*!i=apr-fcaxpahnt!*!(up^&2r)p57z0=d$t*pk6*izv@'
204
-
205
- # SECURITY WARNING: don't run with debug turned on in production!
206
178
  DEBUG = True
207
179
 
208
180
  ALLOWED_HOSTS = ['*']
209
181
 
210
-
211
- # Application definition
212
-
213
182
  INSTALLED_APPS = [
214
183
  'accounts.apps.AccountsConfig',
215
184
  'cissapp.apps.CissappConfig',
@@ -228,91 +197,85 @@
228
197
  '127.0.0.1',
229
198
  ]
230
199
 
200
+ STATIC_URL = '/static/'
231
- MIDDLEWARE = [
201
+ STATICFILES_DIRS = [
232
- 'django.middleware.security.SecurityMiddleware',
233
- 'django.contrib.sessions.middleware.SessionMiddleware',
234
- 'django.middleware.common.CommonMiddleware',
202
+ os.path.join(BASE_DIR, 'static'),
235
- 'django.middleware.csrf.CsrfViewMiddleware',
236
- 'django.contrib.auth.middleware.AuthenticationMiddleware',
237
- 'django.contrib.messages.middleware.MessageMiddleware',
238
- 'django.middleware.clickjacking.XFrameOptionsMiddleware',
239
- 'debug_toolbar.middleware.DebugToolbarMiddleware', # Deubg tool bar
240
203
  ]
204
+ ```
205
+ vote.js
206
+ ```ここに言語を入力
207
+ $(function(){
208
+ // setup for ajax
209
+ var csrftoken = getCookie('csrftoken');
210
+ $.ajaxSetup({
211
+ beforeSend: function(xhr, settings) {
212
+ if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
213
+ xhr.setRequestHeader("X-CSRFToken", csrftoken);
214
+ }
215
+ }
216
+ });
241
217
 
242
- ROOT_URLCONF = 'CISS.urls'
218
+ var votedList = [];// 連打防止用のコメントID格納リスト
219
+ // いいねボタン押下時の処理
220
+ onClickVoteButton();
243
221
 
222
+ function getCookie(name) {
244
- TEMPLATES = [
223
+ var cookieValue = null;
245
- {
246
- 'BACKEND': 'django.template.backends.django.DjangoTemplates',
224
+ if (document.cookie && document.cookie !== '') {
225
+ var cookies = document.cookie.split(';');
226
+ for (var i = 0; i < cookies.length; i++) {
227
+ var cookie = jQuery.trim(cookies[i]);
247
- 'DIRS': [os.path.join(BASE_DIR, 'templates')],
228
+ // Does this cookie string begin with the name we want?
248
- 'APP_DIRS': True,
249
- 'OPTIONS': {
250
- 'context_processors': [
251
- 'django.template.context_processors.debug',
252
- 'django.template.context_processors.request',
253
- 'django.contrib.auth.context_processors.auth',
254
- 'django.contrib.messages.context_processors.messages',
229
+ if (cookie.substring(0, name.length + 1) === (name + '=')) {
230
+ cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
255
- ],
231
+ break;
256
- },
232
+ }
257
- },
233
+ }
258
- ]
234
+ }
235
+ return cookieValue;
236
+ }
259
237
 
238
+ function csrfSafeMethod(method) {
239
+ // these HTTP methods do not require CSRF protection
260
- LOGIN_REDIRECT_URL = '/'
240
+ return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
241
+ }
261
242
 
243
+ function onClickVoteButton() {
244
+ $('.vote_button').on('click', function() {
245
+ var commentId = $(this).data('comment-id');
262
- WSGI_APPLICATION = 'CISS.wsgi.application'
246
+ var currentCount = $(this).data('count');
247
+ var countViewer = $(this).find('.vote_counter');
248
+ if (votedList.indexOf(commentId) < 0) {
249
+ vote(commentId, currentCount, countViewer);
250
+ }
251
+ });
252
+ }
263
253
 
264
-
265
- # Database
266
- # https://docs.djangoproject.com/en/3.1/ref/settings/#databases
267
-
268
- DATABASES = {
269
- 'default': {
254
+ // ajax通信して投票結果を反映する
270
- 'ENGINE': 'django.db.backends.sqlite3',
255
+ function vote(commentId, currentCount, countViewer) {
271
- 'NAME': BASE_DIR / 'db.sqlite3',
256
+ let url = '/api/v1/vote/';
257
+ $.ajax({
258
+ type: 'POST',
259
+ url: url,
260
+ data: {
261
+ comment_id: commentId
262
+ }
263
+ }).then(
264
+ data => {
265
+ if (data.result) {
266
+ countViewer.text(currentCount + 1);
267
+ votedList.push(commentId);
268
+ }
269
+ },
270
+ error => {
271
+ if (error.responseJSON.message) {
272
+ alert(error.responseJSON.message);
273
+ }
274
+ }
275
+ );
272
276
  }
273
- }
274
277
 
275
278
 
276
- # Password validation
279
+ });
277
- # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
278
280
 
279
- AUTH_PASSWORD_VALIDATORS = [
280
- {
281
- 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
282
- },
283
- {
284
- 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
285
- },
286
- {
287
- 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
288
- },
289
- {
290
- 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
291
- },
292
- ]
293
-
294
-
295
- # Internationalization
296
- # https://docs.djangoproject.com/en/3.1/topics/i18n/
297
-
298
- LANGUAGE_CODE = 'ja'
299
-
300
- TIME_ZONE = 'Asia/Tokyo'
301
-
302
- USE_I18N = True
303
-
304
- USE_L10N = True
305
-
306
- USE_TZ = True
307
-
308
-
309
- # Static files (CSS, JavaScript, Images)
310
- # https://docs.djangoproject.com/en/3.1/howto/static-files/
311
-
312
- STATIC_URL = '/static/'
313
- STATICFILES_DIRS = [
314
- os.path.join(BASE_DIR, 'static'),
315
- ]
316
-
317
- #STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
318
281
  ```