Search code examples
djangoformstemplatesreply

Django reply form included into question template


if a have a question - answer system, where the answer form is included in the template of questions,(just like facebook post-comments) is there another way to save the comments for every question? how can i take the id of the question?

my code:

{%include "replies/replies.html"%} #thats in the template where questions are listed

the save_question view

def save_reply(request, id):
   question = New.objects.get(pk = id)
   if request.method == 'POST':
        form = ReplyForm(request.POST)
        if form.is_valid():
           new_obj = form.save(commit=False)
           new_obj.creator = request.user 
           u = New.objects.get(pk=id)
           new_obj.reply_to = u   
           new_obj.save()
           return HttpResponseRedirect('/accounts/private_profile/')    
   else:
           form = ReplyForm()     
   return render_to_response('replies/replies.html', {
           'form': form,
           'question':question, 
           }, 
          context_instance=RequestContext(request))  

and the form:

<form action="." method="post">
<label for="reply"> Comment </label>
<input type="text" name="post" value="">
<p><input type="submit" value="Comment" /></p>
</form>

how can i make this form to work 'embedded' in the questions template, and how can i make it to 'know' the id of the question it reffers to?

Thx


Solution

  • in your replies.html have:

    <form action="." method="post">
        <input type="hidden" value="{{ in_reply_to_id }}" />
        <label for="reply"> Comment </label>
        <input type="text" name="post" value="">
        <input type="submit" value="Comment" />
    </form>
    

    then in your question template:

    <div class="question" id="question-{{ question.id }}">
        {{ question.text }}
        {% with question.id as in_reply_to_id %}
            {%include "replies/replies.html" %}  <--- in_reply_to_id is sent to the include
        {% endwith %}
    </div>
    

    in this way, your main templates can call

    <p> questions here! <p>
    <div class="question-list">
    {% for question in question_list %}
        {% include "questions\question.html" %}
    {% endfor %}
    </div>
    

    Include a little bit of ContentTypes magic, and you can have your replies class reply to any kind of object, not just questions!