[Fixed]-Django form textarea doesn't appear in template

0πŸ‘

βœ…

  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 πŸ™‚

1πŸ‘

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.

πŸ‘€sparkling_joe

0πŸ‘

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)
πŸ‘€Paulo Pessoa

Leave a comment