问题
I'm new in Django and I'm trying to create a form. The thing is that when I render the form, the textfield doesn't appear, but the button does.
The project is a twitter-like app, the form is where the user puts the text to then post it.
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())
view.py:
class PostTweet(View):
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] == "#": #Separamos todas las letras del tweet y si empieza con #, se va a crear un hashtag de esa palabra
hashtag, created = HashTag.objects.get_or_create(name=word[1:])
hashtag.tweet.add(tweet)
return HttpResponse('/user/' +username)
model.py:
class HashTag(models.Model):
#HashTah Model:
name = models.CharField(max_length=64, unique=True)
tweet = models.ManyToManyField(Tweet)
def __unicode__(self):
return self.name
template:
{% 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>
{% for tweet in tweets %}
<div class="well">
<span>{{ tweet.text }}</span>
</div>
{% endfor %}
</div>
</div>
{% endblock %}
image of template: enter image description here
回答1:
The problem is that you don't passing your form into your template. Your can do it by inheriting
get_context_datamethod in your view.Use
FormViewinstead of simpleView, defineform_classandtemplate_name, and it will work. Instead ofpostmethod, useform_validandform_invalidmethods to handle vaild and invalid response, if you need. Since you are usingModelForm, you can omit all methods and keep this view as simple as possible, just addingsuccess_urlproperty to it.
Please read information about ClassBased views, and dig into FormView. It will help :)
回答2:
You have to use context_processors. Below is my use of context processor for one of my websites.
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, "templates")],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'**newsletter.context_processors.form_signup**'
],
},
},
]
context_processors.py(This is inside my newsletter app)
from .forms import SignUpForm
def form_signup(request):
context = {'form_signup': SignUpForm()}
return context
Now your {{ form_signup }} should appear on any template.
回答3:
Try add in class, the form class,
class PostTweet(View):
form_class = TweetForm
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] == "#": #Separamos todas las letras del tweet y si empieza con #, se va a crear un hashtag de esa palabra
hashtag, created = HashTag.objects.get_or_create(name=word[1:])
hashtag.tweet.add(tweet)
return HttpResponse('/user/' +username)
来源:https://stackoverflow.com/questions/33006166/django-form-textarea-doesnt-appear-in-template