我正在尝试做什么:
翻译输入 - >猪拉丁onclick和显示输出。请参阅以下代码:
class translator:
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))
发生了什么:
一旦我运行本地服务器,上面的输入提示^就出现在控制台中,如下所示:
问题是,我想让它出现在我的浏览器中。相反,当我点击我的“翻译”按钮时,它只是在输出部分重复我的翻译div。 (为清楚起见,请参见下图。)
其他相关代码/文件结构:
Views.py
from django.shortcuts import render
from django.http import HttpResponse
from pigLatinApp import pigLatinTranslator
def index(request):
return render(request, 'pigLatinApp/home.html')
def output(request):
if request.is_ajax():
py_obj = pigLatinTranslator.translator
return render(request, 'pigLatinApp/home.html', {'output': py_obj})
模板
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>
</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!">
<button id="translateToPig" class="btn btn-success form-control">Translate</button>
<div id="displayTranslation">
</div>
</form>
</div>
</div>
<script type='text/javascript' src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js">
</script>
<script>
$("#translateToPig").click(function(evt) {
evt.preventDefault();
evt.stopPropagation();
$.get("/output/", function(data) {
$("#displayTranslation").html(data);
}, "html");
});
</script>
{% endblock %}
答案 0 :(得分:0)
在代码中发出print
命令时,其输出将打印在开发服务器的控制台中。使用Django进行编程时,除了调试之外,不需要在代码中使用print
。
使用Python内置的input
仅在命令行上有用。此方法不应用于创建网页。
如果您想在浏览器中获得一些用户输入,可以使用django表单来处理它 你可以做类似的事情:
class TranslateForm(forms.Form):
translation_input = forms.CharField()
然后在视图中使用该表单并获取用户输入 请查看forms的官方文档。
您可以跳过表单,因为它只是一个输入字段,并通过request
获取用户输入。为此,<input>
元素需要属性name
。然后在视图(def output
)中,您可以通过以下方式访问它:
request.GET.get('name', None) # name is the value of attribute name
GET是HTTP方法,如果您需要将其更改为POST,但对于您的情况,GET是适当的方法。