【问题标题】:Django reply form included into question template问题模板中包含 Django 回复表单
【发布时间】:2011-03-12 06:51:21
【问题描述】:

如果有一个问答系统,其中答案表格包含在问题模板中,(就像 facebook post-cmets 一样)是否有另一种方法可以为每个问题保存 cmets?如何获取问题的 ID?

我的代码:

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

save_question 视图

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))  

和形式:

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

我怎样才能让这个表单“嵌入”到问题模板中,我怎样才能让它“知道”它所引用的问题的 ID?

谢谢

【问题讨论】:

  • 如果行 u = New.objects.get(pk=id) new_obj.reply_to = u 您不必要地访问数据库,为什么不只使用“问题”变量?

标签: django forms templates reply


【解决方案1】:

我建议你在http://docs.djangoproject.com/en/1.2/ref/contrib/comments/#ref-contrib-comments-index阅读有关 cmets 的内容,特别阅读 django/contrib/cmets 中的代码标签“render_comment_list”和“render_comment_form”,也许你可以使用 cmets 框架之类的答案,进行“hack”阅读这部分:http://docs.djangoproject.com/en/1.2/ref/contrib/comments/custom/.

【讨论】:

    【解决方案2】:

    另一种方法是在 conf 或您的 urls.py 中:

    (r'^reply/(?P<id>\d+)/$',save_reply),
    

    并以您的形式:

    <form action="/reply/{{ question.id }}/" method="post">
    

    【讨论】:

    • 等一下,我会检查一下并返回详细信息
    • 我认为您必须更改模板 question.html 的 render_to_response
    【解决方案3】:

    在您的replies.html 中有:

    <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>
    

    然后在您的问题模板中:

    <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>
    

    这样你的主模板就可以调用

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

    包含一点 ContentTypes 魔法,您可以让您的回复类回复任何类型的对象,而不仅仅是问题!

    【讨论】:

    • 我能问一下这个有人否决的答案有什么问题吗?
    猜你喜欢
    • 2014-05-13
    • 2011-08-24
    • 2021-09-10
    • 2017-12-04
    • 2017-03-18
    • 2017-04-05
    • 2020-07-09
    • 2012-03-16
    • 1970-01-01
    相关资源
    最近更新 更多