无法查看表单输入字段

时间:2015-12-11 17:27:11

标签: python django

我想收集用户输入的内容,然后使用POST方法更改数据库。但是当我点击网站上的帖子按钮时,我只是空白。

这是views.py

class PostTweet(View):

def post(self, request, username):

    form = TweetForm(request.POST)
    print form.is_valid()
    print request.POST
    print form.errors
    if form.is_valid():
        user = User.objects.get(username=username)
        tweet = Tweet(text=form.cleaned_data['text'],
                      user=user,
                      country=form.cleaned_data['country'])
        tweet.save()
        return HttpResponseRedirect('/user/'+username)
    else:
        form = TweetForm()

    return render(request, 'profile.html', {'form':form})

class Profile(View):
    """
    User Profile page reachable from /user/<username> URL
    """
    def get(self, request, username):
        params = {}
        user = User.objects.get(username = username)
        tweets = Tweet.objects.filter(user=user)
        params["tweets"] = tweets
        params["user"] = user
        return render(request, 'profile.html', params)

forms.py

from django import forms

class TweetForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea, max_length=160)
    country = forms.CharField(widget=forms.HiddenInput(),required=False)

profile.html

{% extends "base.html" %}
{% block content %}
<div class="row clearfix">
  <div class="col-md-6 col-md-offset-3 column">
    <form id="form" method="POST" action="post/">{% csrf_token %}
      <div class="col-md-8 fieldWrapper">
        {{ form }}
        <span class="input-group-btn">
          <button class="btn btn-default" type="submit">Post</button>
        </span>
      </div>
    </form>
  </div>
  <h3>&nbsp;</h3>
  <div class="col-md-12 column">
    {% for tweet in tweets %}
      <div class="well">
        <span>{{ tweet.text}}</span>
      </div>
    {% endfor %}
  </div>
</div>
{% endblock %}

这是urls.py

from django.conf.urls import include, url, patterns
from django.contrib import admin
from tweets.views import Index, Profile, PostTweet, HashTagCloud
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', Index.as_view()),
    url(r'^user/(\w+)/$', Profile.as_view()),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^user/(\w+)/post/$', PostTweet.as_view()),
    url(r'^hashTag/(\w+)/$', HashTagCloud.as_view()),
)

任何人只是给我一个提示将不胜感激: - )

1 个答案:

答案 0 :(得分:0)

仅添加{{form}}不应该呈现该字段。 form是一个以字段作为属性的对象。在你的html尝试用{{form}}替换{{form.text}}

您也可以尝试传递对象“表单”,如下所示:

return render(request, 'profile.html', form = form)