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

質問編集履歴

3

わかりやすく

2021/05/15 12:06

投稿

Mitsu_
Mitsu_

スコア10

title CHANGED
File without changes
body CHANGED
@@ -1,19 +1,42 @@
1
1
  ### 前提・実現したいこと
2
2
 
3
3
  お世話になります。
4
+ メルカリのようなサイトを作っており、
4
- 、とても簡単なッセージアプリを作っております
5
+ ルカのコメント機能のところを作っております
5
- 送信受信はできるのですが、ページをリロードしなければ相手のッセージを取得することができないため、Ajaxを用いてメッセージを5秒間隔くらいで自動で取得したいです。
6
+ ![イメージ説明](60e842999bdb7bdec369d7dae647be21.png)
6
7
 
7
- そこでHTMLへ書き方と、views.py, urls.pyでの書き方ご教授願いたいです。
8
+ 相手からコメントAjaxを使って自動的に取得したいです。
8
9
 
10
+ ### 発生している問題
11
+ 下のhtmlのscriptタグのソースコードは、以前授業でflaskを用いてメッセージアプリを作ったときに、
12
+ 相手からのメッセージを自動で取得するために用いたものです。
13
+ これを今、私が作っているDjangoのアプリに取り入れ用としたところ、<script>タグ内の中の
9
- 初心者ため、DjagoでAjaxの書き方調べてもわからなかったため、質問させていただきました。 
14
+ {{to_user_id}}部分,つまり相手側idをどようにけばいいのかがわから、質問させていただきました。
15
+ 自分側のidは request.user.idで取得できております。
10
- 初心者ゆえ、足りない情報がございましたら、アップいたしますので、どうぞよろしくお願いいたします。
16
+ どうぞよろしくお願いいたします。
11
17
 
18
+ **html**
19
+ ```
20
+ <script>
21
+ $(function(){
22
+ // 5秒間隔でget_new_messagesを実行
23
+ timer = setInterval("get_new_messages()", 5000);
24
+ // 初期表示で画面の一番下に行く
25
+ var scroll = (document.scrollingElement || document.body);
26
+ scroll.scrollTop = scroll.scrollHeight;
27
+ });
28
+ user_id = "{{ to_user_id }}";
29
+ function get_new_messages(){
30
+ $.getJSON("/message_ajax", {
31
+ user_id: user_id
32
+ }, function(data){
33
+ $('#message-form').before(data['data']);
34
+ });
35
+ };
36
+ </script>
12
37
 
38
+ <h3 class="text-center">商品名: {{product.product_name}}</h3>
13
39
 
14
- ### 該当のソースコード
15
- **html**
16
- ```
17
40
  <div class="row">
18
41
  {% for comment in comments%}
19
42
  {% if comment.user.id == request.user.id %}
@@ -39,10 +62,7 @@
39
62
  <div class="col-lg-7"></div>
40
63
  {% endif %}
41
64
  {% endfor %}
42
- <br>
65
+
43
- <br>
44
- <hr>
45
- <br>
46
66
  {% if user.is_authenticated %}
47
67
  <div class="col-4 offset-7" id="message-form">
48
68
  <form method="POST">
@@ -54,64 +74,46 @@
54
74
  {% endif %}
55
75
 
56
76
  </div>
57
- {% endblock %}
58
77
  ```
78
+ メッセージを保管しているDB
79
+ product_idはユーザー登録した人が出品した商品のidです。
80
+ user_idはコメントを書いた人のidです。
81
+ ![イメージ説明](13ad0e089bdb4abbb9ff477ae5fb3583.png)
59
82
 
60
83
 
61
84
 
85
+ ### 該当のソースコード
62
86
 
63
-
64
- ### 試したこと
87
+ models.py
65
- flaskではこのようなやり方をしていたのですが、これをどのようにDjangoにあてはめるのかがわからないです。
66
- どうぞよろしくお願い申し上げます
67
-
68
- **html**
69
88
  ```
70
- <script>
71
- $(function(){
72
- // 5秒間隔でget_new_messagesを実行
73
- timer = setInterval("get_new_messages()", 5000);
74
- // 初期表示で画面の一番下に行く
75
- var scroll = (document.scrollingElement || document.body);
76
- scroll.scrollTop = scroll.scrollHeight;
89
+ class Comments(models.Model):
77
- });
78
- user_id = "{{ to_user_id }}";
90
+ comment = models.CharField(max_length=1000)
91
+ user = models.ForeignKey('SellText.Users', on_delete=models.CASCADE)
92
+ product = models.ForeignKey('SellText.Product',on_delete=models.CASCADE)
79
- function get_new_messages(){
93
+ objects = CommentsManager()
80
- $.getJSON("/message_ajax", {
81
- user_id: user_id
82
- }, function(data){
94
+ class Meta:
83
- $('#message-form').before(data['data']);
84
- var checked_message_ids = data['checked_message_ids'];
85
- for(let idx = 0; idx < checked_message_ids.length; idx++){
86
- $('#self-message-tag-'+checked_message_ids[idx]).append('<p>既読</p>');
87
- }
88
- });
89
- };
90
- </script>
95
+ db_table='comments'
91
96
  ```
92
- **views.py**
97
+ views.py
93
98
  ```
94
- @bp.route('/message_ajax', methods=['GET'])
95
- @login_required
96
- def message_ajax():
97
- user_id = request.args.get('user_id', -1, type=int)
98
- # まだ読んでいない相手からのメッセージを取得
99
- user = User.select_user_by_id(user_id)
100
- not_read_messages = Message.select_not_read_messages(user_id, current_user.get_id())
101
- not_read_message_ids = [message.id for message in not_read_messages]
102
- if not_read_message_ids:
103
- with db.session.begin(subtransactions=True):
104
- Message.update_is_read_by_ids(not_read_message_ids)
105
- db.session.commit()
106
- # すでに読まれた自分のメッセージでまだチェックしていないものを取得
107
- not_checked_messages = Message.select_not_checked_messages(current_user.get_id(), user_id)
108
- not_checked_message_ids = [not_checked_message.id for not_checked_message in not_checked_messages]
109
- if not_checked_message_ids:
99
+ def post_comment(request, product_id):
110
- with db.session.begin(subtransactions=True):
111
- Message.update_is_checked_by_ids(not_checked_message_ids)
112
- db.session.commit()
113
- return jsonify(data=make_message_format(user, not_read_messages), checked_message_ids = not_checked_message_ids)
114
100
 
101
+ comments_form =forms.CommentForm(request.POST or None)
102
+ # comment_product = Comments.objects.all()
103
+ product = Product.objects.get(id=product_id)
104
+ comments = Comments.objects.fetch_by_product_id(product_id)
105
+
106
+ if comments_form.is_valid():
107
+ if not request.user.is_authenticated:
108
+ raise Http404
109
+ comments_form.instance.product = product
110
+ comments_form.instance.user = request.user
111
+ comments_form.save()
112
+
113
+ return redirect('SellText:post_comment',product_id=product_id)
114
+ return render(request,'comment.html', context={
115
+ 'comments_form':comments_form,
116
+ 'comments':comments,
117
+ 'product':product
118
+ } )
115
- ```
119
+ ```
116
- u
117
- ネットやJavascriptの本を購入し調べたのですが、Djangoでの書き方や応用が分からずにいます。

2

詳しく

2021/05/15 12:06

投稿

Mitsu_
Mitsu_

スコア10

title CHANGED
File without changes
body CHANGED
@@ -62,5 +62,56 @@
62
62
 
63
63
 
64
64
  ### 試したこと
65
+ flaskではこのようなやり方をしていたのですが、これをどのようにDjangoにあてはめるのかがわからないです。
66
+ どうぞよろしくお願い申し上げます
65
67
 
68
+ **html**
69
+ ```
70
+ <script>
71
+ $(function(){
72
+ // 5秒間隔でget_new_messagesを実行
73
+ timer = setInterval("get_new_messages()", 5000);
74
+ // 初期表示で画面の一番下に行く
75
+ var scroll = (document.scrollingElement || document.body);
76
+ scroll.scrollTop = scroll.scrollHeight;
77
+ });
78
+ user_id = "{{ to_user_id }}";
79
+ function get_new_messages(){
80
+ $.getJSON("/message_ajax", {
81
+ user_id: user_id
82
+ }, function(data){
83
+ $('#message-form').before(data['data']);
84
+ var checked_message_ids = data['checked_message_ids'];
85
+ for(let idx = 0; idx < checked_message_ids.length; idx++){
86
+ $('#self-message-tag-'+checked_message_ids[idx]).append('<p>既読</p>');
87
+ }
88
+ });
89
+ };
90
+ </script>
91
+ ```
92
+ **views.py**
93
+ ```
94
+ @bp.route('/message_ajax', methods=['GET'])
95
+ @login_required
96
+ def message_ajax():
97
+ user_id = request.args.get('user_id', -1, type=int)
98
+ # まだ読んでいない相手からのメッセージを取得
99
+ user = User.select_user_by_id(user_id)
100
+ not_read_messages = Message.select_not_read_messages(user_id, current_user.get_id())
101
+ not_read_message_ids = [message.id for message in not_read_messages]
102
+ if not_read_message_ids:
103
+ with db.session.begin(subtransactions=True):
104
+ Message.update_is_read_by_ids(not_read_message_ids)
105
+ db.session.commit()
106
+ # すでに読まれた自分のメッセージでまだチェックしていないものを取得
107
+ not_checked_messages = Message.select_not_checked_messages(current_user.get_id(), user_id)
108
+ not_checked_message_ids = [not_checked_message.id for not_checked_message in not_checked_messages]
109
+ if not_checked_message_ids:
110
+ with db.session.begin(subtransactions=True):
111
+ Message.update_is_checked_by_ids(not_checked_message_ids)
112
+ db.session.commit()
113
+ return jsonify(data=make_message_format(user, not_read_messages), checked_message_ids = not_checked_message_ids)
114
+
115
+ ```
116
+ u
66
117
  ネットやJavascriptの本を購入し調べたのですが、Djangoでの書き方や応用が分からずにいます。

1

わかりやすく

2021/05/15 05:50

投稿

Mitsu_
Mitsu_

スコア10

title CHANGED
File without changes
body CHANGED
@@ -6,9 +6,11 @@
6
6
 
7
7
  そこでHTMLへの書き方と、views.py, urls.pyでの書き方をご教授願いたいです。
8
8
 
9
- 初心者のため、DjagoでのAjaxの書き方が調べてもわからなかったため、質問させていただきました。 足りない情報がございましたら、アップいたしますので、どうぞよろしくお願いいたします。
9
+ 初心者のため、DjagoでのAjaxの書き方が調べてもわからなかったため、質問させていただきました。 
10
+ 初心者ゆえ、足りない情報がございましたら、アップいたしますので、どうぞよろしくお願いいたします。
10
11
 
11
12
 
13
+
12
14
  ### 該当のソースコード
13
15
  **html**
14
16
  ```