Django pass input data from an HTML file to a python script and then send the final data to another HTML file

Viewed 610

I'm trying to build a simple dictionary in Django. In the home.html file there's a form, which asks the user to enter a word. This word should 'become a variable' in a python script which needs it to retrieve certain data from an API.

import json
import urllib.request

url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/' + user_input

response = urllib.request.urlopen(url)
result = json.loads(response.read())

final_word = str(result[0]['word']) + ' \n\n'

final_def = str(result[0]['meanings'][0]['definitions'][0]['definition']))

'user_input' would be the variable where the input is stored

It should then pass the data obtained from the API (in this case final_word and final_def to another HTML file, final.html

I can't figure out how to do this. Any help is appreciated. Comment if I need to add some of the code. Forgive my bad english.

1 Answers

So if your trying to do this in a view. Assumming you have two templates

from django.shortcuts import render 
import urllib.request
import json

def home(request): # your view name
    if request.POST:
        url = 'https://api.dictionaryapi.dev/api/v2/entries/en_US/' + request.POST['user_input']
        response = urllib.request.urlopen(url)
        result = json.loads(response.read())
        context = {'word':result[0]['word'], 'meanings':result[0]['meanings']}
        return render(request, 'output.html', context)
    return render(request,'input.html')

Heres a quick html templates to use
input.html

<html>
    <form action="#" method="post">
        {% csrf_token %}
        <input type="text" name="user_input">
        <button>Go</button>
    </form>
</html>

And the test output
output.html

<html>
    <p>word: {{word}}</p>
    <p>meaning: {{ meanings }}</p>
</html>
Related