0
votes

I am trying to print the POST data from django form on my webpage, right under my form. I am able to print it by HttpResponse on a different page, but I want it on the same page when the user presses submit button.

Views.py

    from django.views.generic import TemplateView
    from django.shortcuts import render
    from django import forms
    from django.http import HttpResponseRedirect, HttpResponse
    from home.forms import HomeForm

   def home(request):
        def get(request):
        form = HomeForm()
        return render(request, 'home/home.html', {'form':form})

   if request.method=='GET':
        response=get(request)
        return response

   elif request.method == 'POST':
    
       form = HomeForm(request.POST)
       if form.is_valid():
        text = HomeForm('post')
        return HttpResponse('post')
    
    

   else:
      form = HomeForm()
   return render(request, 'home/home.html', {'form':form})

Forms.py

from django import forms

class HomeForm(forms.Form):
  post = forms.CharField( widget= forms.TextInput() )
  

Html template

<div class="container">
<form method='post'>

{% csrf_token %}
{{ form.as_p }} 
<input type="submit" value="submit" class="btn btn-danger">

</form>
<h2>{{ text }}</h2>
</div>

I want the post field input to be displayed in the 'text' mentioned in the h2 tag of the webpage as soon as the user presses the submit button, and not on a separate page like HttpResponse does.

1

1 Answers

0
votes

You have three options to get this thing done : First is, you redirect the form on submit to the same page and pass the request.POST.DATA in context and then you can easily display it. Like :

def home(request):
        def get(request):
        form = HomeForm()
        return render(request, 'home/home.html', {'form':form})

   if request.method=='GET':
        response=get(request)
        return response

   elif request.method == 'POST':
    
       form = HomeForm(request.POST)
       if form.is_valid():
        text = HomeForm('post')
        # return HttpResponse('post')
        context = {'text' : text, 'form' : form,}
        return render(request, 'home/home.html', context)
    
    

   else:
      form = HomeForm()
   return render(request, 'home/home.html', {'form':form})

Second Option is To display itself in the form the initial values from the Model :

form = HomeForm(initial = {'text' : modelsFile.Model.object}) # models.ModelName.text

Third Option is to use JavaScript and JQuery for realtime display of data. That would be complex but good to do, you can search for how to display form data realtime in JS on google. Thank you.