2017-03-23 10 views
0

フォーラムアプリケーションの質問ページの一部として、各ページに複数の投稿が含まれています。そのうちの1つは質問です。各投稿には多くのコメントが含まれています。しかし、1ページには多くの投稿があるので、各コメントに割り当てられている投稿をデータベースに渡す方法はわかりません。Django - フォームにテンプレートを渡す

私はHiddenInputを使用することを考えていましたが、実装方法は不明です。

以下のコード: question_page.html

<tr id="post-comment-row"> 
    <!-- Post a comment --> 
    {% if user.is_authenticated %} 
     <tr> 
      <form id="comment_form" method="post" action="." 
        enctype="multipart/form-data"> 
       {% csrf_token %} 
       <!-- Display form --> 
       {{ comment_form.as_p }} 
       <!-- Provide a button to click to submit the form --> 
       <input type="submit" name="submit" value="Post"> 
      </form> 
     </tr> 
    {% else %} 
     Please login to post a comment 
    {% endif %} 
</tr> 

views.py:

# Show each individual question 
def show_question_page(request, module_name_slug, question_page_name_slug, post_context=None): 
    context_dict = {} 

    module = Module.objects.get(slug=module_name_slug) 
    question_page = QuestionPage.objects.get(slug=question_page_name_slug) 
    question_posts = QuestionPost.objects.filter(page=question_page) 
    comments = Comment.objects.filter(post__in=question_posts) 

    if request.method == 'POST': 
     comment_form = CommentForm(data=request.POST) 
     if comment_form.is_valid(): 
      # Save user data to database 

      # Save comment instance 
      comment = comment_form.save(commit=False) 
      comment.post = post_context 
      comment.user_profile = UserProfile.objects.filter(user=request.user) 
      comment.save() 
     else: 
      # Invalid form(s): Print errors to console/log 
      print(comment_form.errors) 
    else: 
     comment_form = CommentForm 

    context_dict['question_posts'] = question_posts 
    context_dict['question_page'] = question_page 
    context_dict['comments'] = comments 
    context_dict['module'] = module 
    context_dict['comment_form'] = comment_form 

    return render(request, 'forum/questionPage.html', context_dict) 

答えて

1

あなたはコメントをされているポストのidをキャプチャするpost.idためnamed groupでURLを作成する必要があります作成されます。

url(r'app/post/(?P<post_id>\d+)/comment/create', show_question_page, name='create-comment') 

フォームのアクションURLにpost.idを渡すことができます。

action={% url 'create-comment' post.id %} 

とビューでは、あなたはリクエストオブジェクトから渡されたpost_idを取得し、ポストに関連するコメントを作成することができます。

comment = comment_form.save(commit=False) 
    post_id = request.POST.get('post_id') 
    comment.post = get_object_or_404(QuestionPost, id=post_id) 
    comment.user_profile = UserProfile.objects.filter(user=request.user) 
+0

乾杯!地獄で数時間それについていく –

+0

@MatthewDay大歓迎です。 –

関連する問題