2

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 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

It worked! I just had to make some changes to make it output what I wanted :D I removed the 2nd return in the views file in ` <form action="#" method="post"> ` I replaced # with the /result/ directory I replaced 'meanings' with 'definition' in 'context' (like this ` 'definition':result[0]['meanings'][0]['definitions'][0]['definition']` ) Thank you very much

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.