Django - 将模板上下文传递给表单

时间:2017-03-23 18:00:17

标签: python html css django web-services

作为论坛应用的问题页面的一部分,每个页面都包含多个帖子,其中一个是一个问题。每篇文章可能有很多评论。但是,由于每页有很多帖子,我不知道如何将每条评论分配到数据库的帖子传递。

我正在考虑使用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 个答案:

答案 0 :(得分:1)

您需要为renew创建一个named group的网址,以捕获正在为其创建评论的帖子的post.id

id

您可以在表单的操作网址中传递url(r'app/post/(?P<post_id>\d+)/comment/create', show_question_page, name='create-comment')

post.id

在视图中,您可以从请求对象获取传递的action={% url 'create-comment' post.id %} ,并创建与帖子相关的评论。

post_id