Search code examples
pythonhtmldjangowebdjango-views

Not showing text in html with POST request


Im trying to take a text from a text box and print it on my html file, but it doesn't work.

Here is my views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import InputForm
# Create your views here.

def home(request):
    form = InputForm()
    return render(request, 'index.html', {'form': form })

def post(request):
    form = InputForm(request.POST)
    if form.is_valid():
        text = form.cleaned_data['post']

        args = {'form': form, 'text': text}
    return render(request, 'index.html', args)

Here is my index.html

{% block content %}
<h1>Write a sentence</h1>

<form method="post" action="">
    {{ form }}
    {% csrf_token %}
    <button type="submit", name="save">Generate</button>
</form>
<h2>
    {{ text }}
</h2>

{% endblock %}

forms.py

''' from django import forms

class InputForm(forms.Form): input = forms.CharField(label="Text", max_length=1000) '''

Im doing all stuff by tutorial and getting POST request in terminal, but unfortunately text doesn't appear


Solution

  • You are firing the home function again. You should handle the POST case there as well:

    def home(request):
        text = ''
        if request.method == 'POST':
            form = InputForm(request.POST, request.FILES)
            if form.is_valid():
                text = form.cleaned_data['post']
        else:
            form = InputForm()
        return render(request, 'index.html', {'form': form, 'text': text})