Matthew Day Matthew Day -4 years ago 156
CSS Question

Django - Passing template context to form

As part of a question page for a forum app, each page contains multiple posts, one of which is a question. Each post may have many comments. However, because there are many posts per page, I do not know how to pass the post that each comment is assigned to up to the database.

I was thinking of using HiddenInput, but not sure how to implement it.

Code below:
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)

Answer Source

You will need to create a url with named group for post.id to capture the id of post for which comment is being created.

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

You can pass post.id in action url of the form.

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

And in view, you can get the passed post_id from request object and create a comment related to post.

    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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download