0

I found a couple of resources online, but none that worked for me. Here is what I currently have:

In views.py:

def button(request):
    return render(request, 'home.html')

def display_text(request):
    return HttpResponse('TESTING', status=200)

In urls.py:

urlpatterns = [
    url(r'^$', views.button),
    url(r'^display_text', views.display_text, name='script'),
]

In home.html:

      <div class="row">
        <input type="text" class="form-control js-text" id="input-box" placeholder="Type something to begin..."/>
        <div class="col-md-12" style="text-align:center;">
            <button onclick="location.href='{% url 'script' %}'"></button> <hr>
        </div>
      </div>

What happens right now is that it displays the string on a new web page. What I want to do is populate my text-box with that string returned by my Python function, and display it on the current page. How can I do so? Thanks!

Shawn Zhang
  • 1,719
  • 2
  • 14
  • 20

1 Answers1

1

The easiest way to do this is to make use of the render function provided by Django. This function combines a context and a template and renders a HttpResponse. You can change the display_text function to the following:

def display_text(request):
    return render(request, 'home.html', {'string': 'TESTING'})
    #Im assuming home.html is the the page you want to render

Now you can make use of Django templates to show the data sent through the context like so:

<div>
    <p>{{string}}</p>
</div>
friedteeth
  • 61
  • 1
  • 1
  • When I do this, I am redirected to another page with '/display_text' at the end. How can I do it so I am not redirected to that page, nor do I refresh my page. – Shawn Zhang May 13 '20 at 07:27
  • 1
    Ok, so if you do not want your page to reload, that is a whole different topic. What you should be making use of is Ajax. Ajax is for creating asynchronous web apps, which in other words it can make petitions and receive responses without reloading your web page. I recommend starting here [link](https://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications), it provides an awesome example and simple example of Ajax with Django. – friedteeth May 13 '20 at 07:38