在页面上显示Django表单

时间:2014-11-20 02:02:57

标签: django django-models django-views

我正在尝试在页面上显示评论表单。到目前为止,我已经创建了一个链接,我希望每次单击该链接时,它会在链接所在的同一页面上显示该表单,但我的问题是该链接将我重定向到另一个页面,我不想要

urls.py

url(r'^all/$', 'posts.views.articles'),
        url(r'^get/(?P<post_id>\d+)/$', 'posts.views.article'),
        url(r'^articles/$', 'posts.views.create'),
        url(r'^like/(?P<post_id>\d+)/$', 'posts.views.like_article'),
        url(r'^article/(?P<post_id>\d+)/$', 'posts.views.add_comment'),

views.py

    def articles(request):
        args = {}
        args.update(csrf(request))
        args ['posts'] = post.objects.filter(user = request.user)
        args ['full_name'] = User.objects.get(username = request.user.username)
        args ['form'] = PostForm()



        return render_to_response('articles.html', args)

    def article(request, post_id=1):

        return render(request, 'article.html', 
                      {'post': post.objects.get(id=post_id) })
def add_comment(request, post_id):
    a = post.objects.get(id=post_id)

    if request.method == "POST":
        f = CommentForm(request.POST)
        if f.is_valid():
            c = f.save(commit=False)
            c.pub_date = timezone.now()
            c.article = a
            c.save()

            messages.success(request, "You Comment was added")

            return HttpResponseRedirect('/posts/get/%s' % post_id)

    else:
        f = CommentForm()

    args = {}
    args.update(csrf(request))

    args['post'] = a
    args['form'] = f

    return render_to_response('article.html', args)
    #return HttpResponseRedirect('/posts/all')

article.html

<h2>Comments</h2>
{% for c in post.comment_set.all %}
<p>{{c.name}} : {{c.body}}</p>
{% endfor %}


<form action="/posts/article/{{post.id}}/" method="post">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>

<input type="submit" name="submit" value="Post Comment">
</form>

{% endblock %}

2 个答案:

答案 0 :(得分:2)

从你的问题中,你想在你的文章中提交评论,当你提交评论时,你想将它重定向到相同的文章页面...如果你愿意这样做,那么这里就是例子:

首先使用模型表单或仅使用表单创建评论提交表单:

class CommentCreationForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('comment_body',) # Set your field for comment

现在将此表单作为文章视图中的上下文传递。就像你上面那样。

def articles(request):
    args = {}
    args.update(csrf(request))
    args ['posts'] = post.objects.filter(user = request.user)
    args ['full_name'] = User.objects.get(username = request.user.username)
    args ['comment_form'] = CommentCreationForm
    return render_to_response('articles.html', args)

您的article.html

<h2>Comments</h2>
{% for c in post.comment_set.all %}
<p>{{c.name}} : {{c.body}}</p>
{% endfor %}


<form action=""{% url "comment_submit" post.id %}"" method="get">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>

<input type="submit" name="submit" value="Post Comment">
</form>

{% endblock %}

使用url(r'^comment/(?P<pk>\d+)/',CommentSubmitView, name="comment_submit"),抓住网址并撰写视图。

def AnswerSubmitView(request, pk):


post = Post.objects.get(id=pk) # Get what you have set for your article
comment_text = request.GET.get('comment_body',False)

com = Comment()
post = post # or anything that you have named for your article..
com.comment_body = comment_text
com.save()


return HttpResponseRedirect('/post/%s' % pk) # Your url for your article I guess...

...享受

答案 1 :(得分:0)

使用ajax调用从服务器获取表单而不刷新页面。这需要jQuery。将我用过的占位符选择器替换为您的应用所需的任何内容。我建议将所有article.html包装在div中,并为其指定一个id标记(并参考我在下面使用&#39;#form-id&#39;选择器的标签),这样您就知道表单已经显示,您可以访问整个块。

另请注意,我并不完全确定如何从render_to_response获取HTML。只需弄清楚将哪种对象发送回ajax调用者以及如何从该对象获取html。不应该很难。

调整并将以下内容添加到模板的底部,其中包含添加表单的链接

<script>
var showForm = function(url) {
            $.ajax({
                type: 'GET',
                dataType: 'json',
                url: url,
                success: function(data, status, xhr) {
                    // Not positive if this is how things work with render_to_response
                    // I usually use render_to_string for this and just return pure HTML
                    $('#div-to-display-form-in').append(data);
                },
                error: function(error) {
                    // Handle error
                }
            });
        }

    $(document).ready(function() {

       $('#link-to-show-form').click(function(event) {
            event.preventDefault();

            // The conditionals check if form is already showing
            // If form already showing and link clicked again, form is removed
            if ($('#form-id').length === 0) {
                showForm($(this).attr('href'));
            } else {
                $('#form-id').remove();
            }
        });

    });
</script>