我是Django的初学者,我试图创建一个表单。问题是,当我渲染表单时,Textarea
字段不会显示,但按钮会显示。
该项目是一个类似Twitter的应用程序,表单是用户将文本放入的位置,然后发布。
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())
class PostTweet(View):
"""Tweet Post form available on page /user/<username> URL"""
def post(self, request, username):
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)
{% 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>
<h3> </h3>
<div class="col-md-12 column">
{% for tweet in tweets %}
<div class="well">
<span>{{tweet.text}}</span>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
答案 0 :(得分:1)
正如Daniel Roseman所说,你需要定义一个显示表单的GET方法。只需将其添加到PostTweet
班级:
def get(self, request):
form = TweetForm()
return render(request, 'template/path/here.html', {'form': form})
Django Girls有一个nice tutorial on forms。虽然他们的观点与你的观点不是基于类的,但它基本上是相同的。