Django form textarea doesn't appear in template

泪湿孤枕 提交于 2019-12-10 12:13:56

问题


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>&nbsp;</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:


  1. The problem is that you don't passing your form into your template. Your can do it by inheriting get_context_data method in your view.

  2. Use FormView instead of simple View, define form_class and template_name, and it will work. Instead of post method, use form_valid and form_invalid methods to handle vaild and invalid response, if you need. Since you are using ModelForm, you can omit all methods and keep this view as simple as possible, just adding success_url property 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!