从用户输入输入并在同一页面上显示相同的输入

时间:2014-11-18 14:34:24

标签: python django forms

您好我正在尝试在django中创建一个帖子表单,用户创建一个帖子,并且帖子会在同一页面上显示回来,到目前为止我一直没有成功。我的文章显示在页面上,但发布文章的表单不仅仅是提交按钮显示。

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)

    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 create(request):
    if request.POST:
        form = PostForm(request.POST, request.FILES)
        if form.is_valid():
            a = form.save(commit=False)
            a.user = User.objects.get(username = request.user.username)
            a.save()

            messages.add_message(request, messages.SUCCESS, "You Article was added")

            return HttpResponseRedirect('/posts/all')
    else:
        form = PostForm()

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

    args['form'] = form

    return render_to_response('articles.html', args)

articles.html

<form action="/posts/create/" method="post" enctype="multipart/form-data">{% csrf_token %}
<ul>
{{form.as_ul}}
</ul>

<input type="submit" name="submit" value="Create Article">

</form>

{% if posts.count > 0 %}

{% for post in posts %}

    <div>
    <h2><a href="/posts/get/{{ post.id }}/">{{full_name}}</a></h2>
    <p>{{ post.body|lower|truncatewords:50 }}</p>
    <p>{{post.likes}} people liked this article</a></p>
    </div>

{% endfor %}

{% else %}

<p>None to show!</p>

{% endif %}

{% endblock %}

urls.py

from django.conf.urls import patterns, include, url

urlpatterns = patterns('',

        url(r'^create/$', 'posts.views.articles'),
        url(r'^get/(?P<post_id>\d+)/$', 'posts.views.article'),
        url(r'^create/$', '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'),
    )

1 个答案:

答案 0 :(得分:0)

首先,您不能将表单传递给articles()中的模板。你需要有以下几点:

args['form'] = YourForm()

在您的第一个视图功能中。此外,在您的创建视图中,您可以执行以下操作:

a.user = User.objects.get(username = request.user.username)

再次对用户进行不必要的数据库查找,您可以更清晰,更快地执行此操作:

a.user = request.user