表格字段未显示(django 1.7)

时间:2015-10-15 14:19:57

标签: html django forms

表单字段(文本区域)未在我的django模板中显示。我可以找出问题所在。

Views.py

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


class PostTweet(View):
"""Tweet Post form available on page /user/<username> URL"""
def post(self, request, username):
    if request.method == 'GET':
        form = TweettForm()
    else:
        form = TweetForm(self.request.POST)
        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()
            words = form.cleaned_data['text'].split(" ")
            for word in words:
                if word[0] == "#":
                    hashtag, created = HashTag.objects.get_or_create(name=word[1:])
                    hashtag.tweet.add(tweet)
        return HttpResponseRedirect('/user/'+username)

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

forms.py

from django import forms


class TweetForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea(attrs={'rows': 1,     'cols':85}), max_length=160)
    country = forms.CharField(widget=forms.HiddenInput())

profile.html

{% extends "base.html" %}

{% block content %}
<div class="row clearfix">
<div class="col-md-12 column">
    <form method="post" action="post/">{% csrf_token %}
        <div class="col-md-8 col-md-offset-2 fieldWrapper">
            {{ form.text.errors }}
            {{ form.text }}
        </div>
            {{ form.country.as_hidden }}
        <div>
            <input type="submit" value="post">
        </div>
    </form>
</div>

urls.py

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

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

在浏览器中呈现时,只有提交(发布)按钮显示在on上。文字不在那里

1 个答案:

答案 0 :(得分:0)

由于您没有将表单传递给模板,因此没有任何结果。在get视图中编写PostTweet函数,并在其中包含form = TweetForm()作为传递给模板的参数。