简体   繁体   中英

Running python file on HTML button click (Django)

Relevant information:

1) First post on here, go easy.

2) I'm a noob.

3) Trying to learn python/Django.

What I'm trying to do:

1) Create an english -> pig latin translator (written in python) and have it work in browser.

How I want it to work:

1) User clicks "translate" button, which then uses my existing python function to translate their input.

2) The translation is then displayed below the input.

What I've done so far:

1) Created .py file that successfully translates english -> pig latin in the console.

def pigLatin(sentence):
translation = " "
for word in sentence.split():
    if word[0] in "aeiou":
        translation += word + "yay "
    if word[0] and word[1] not in "aeiou":
        translation += word[2:] + word[0:2] + "ay"
        print("hai")
    else:
        translation +=  word[1:] + word[0] + "ay "
return translation

sentence = input("Enter word/sentence you want translated to pig latin below: ")

print(pigLatin(sentence))

2) Used Jinja/added some HTML and bootstrap (please see below)

What it looks like in browser

3) Created a Django project, and installed my pig latin app, my folders are structured as so:

--mysite
|
|--pigLatinApp
|----templates
|------pigLatinApp
|--------home.html
|--------header.html

3) Attempted to use Ajax to get my button working, my HTML files and views.py are as follows:

header.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Pig Latin Translator</title>
    {% load staticfiles %}
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css">
</head>
<body class="body">    

<section id="translatorSection">
<!------------------Log Sum Container-------------------------->
    <div class="container" id="translatorContainer">
        {% block content %}
        {% endblock %}
    </div>           
</section>
<script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
</script>
</body>
</html>

home.html

{% extends "pigLatinApp/header.html" %}

{% block content %}
<div class="row">
    <div class="col-md-6">
        <form>
            <h3>Pig Latin Translator</h3>
                <p>Enter below what you want translated!</p>
                <input type="string" class="form-control" placeholder="Type what you want translated here!" id="inputSumA">
                <button id="translateToPig" class="btn btn-success form-control">Translate</button>
                <div id="displayTranslation">
                    <p>{{ output }}</p>
                </div> 
        </form>     
    </div>   
</div>
<script>
$("#translateToPig").click(function() {
    $.get("/output/", function(data) {
        $("#displayTranslation").html(data);
    }, "html");
});
</script>

{% endblock %}

views.py

from django.shortcuts import render
from django.http import HttpResponse

def index(request):
    return render(request, 'pigLatinApp/home.html')

def output(request):
    if request.is_ajax():
        py_obj = pigLatinTranslator.test_code(10)
        return render(request, 'pigLatinApp/output.html', {'output': py_obj.a})

What actually happens when I click the button:

1) Nothing... The page seems to refresh.

Any and all help would be appreciated, cheers!

Here:

<script>
$("#translateToPig").click(function() {
    $.get("/output/", function(data) {
        $("#displayTranslation").html(data);
    }, "html");
});
</script>

Your click event handler doesn't prevent the event's default action, so your form is submitted by the browser. Since your form has no 'action' attribute it's submitted to the current url, so the index view is called and the page is reloaded.

You can prevent this by calling preventDefault() on the event ie:

 <script>
$("#translateToPig").click(function(evt) {
    evt.preventDefault(); # prevents posting the form
    evt.stopPropagation(); # make sure it doesn't bubble up
    $.get("/output/", function(data) {
        $("#displayTranslation").html(data);
    }, "html");
});
</script>

Now there are a couple things that could be improved in your code but that's another topic. At least I think you should first try to get something working without ajax, so you learn the whole request/response cycle stuff, working with GET and POST, using django forms etc.

I recommend trying a normal request ie not ajax and also creating a form.py where you can create a form class for the search. In your views import the pig latin translator function and call it in your output function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM