Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/289.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在一个Django HttpResponse中返回两个变量?_Python_Json_Django_Http - Fatal编程技术网

Python 如何在一个Django HttpResponse中返回两个变量?

Python 如何在一个Django HttpResponse中返回两个变量?,python,json,django,http,Python,Json,Django,Http,好的,我是django的新手,我正在开发一个非常简单的应用程序。用户在文本框中输入位置,我从谷歌地图获取该位置的坐标,并在下一页打印出来。到目前为止,我已经能够获得JSON文件中的坐标以及许多其他信息。我还成功地分离了纬度和经度,并将它们存储到单独的变量中。但是我没法把它们打印出来。只打印一个值。有人能帮我吗?这是我到目前为止写的: My views.py: from django.shortcuts import render from django.http import HttpRespo

好的,我是django的新手,我正在开发一个非常简单的应用程序。用户在文本框中输入位置,我从谷歌地图获取该位置的坐标,并在下一页打印出来。到目前为止,我已经能够获得JSON文件中的坐标以及许多其他信息。我还成功地分离了纬度和经度,并将它们存储到单独的变量中。但是我没法把它们打印出来。只打印一个值。有人能帮我吗?这是我到目前为止写的: My views.py:

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
import requests
import json
# Create your views here.


def homepage(request):
    if request.method == 'GET':
        return render(request, 'geog/homepage.html')

    if request.method == 'POST':
        string = request.POST['location']
        maps_url = "http://maps.googleapis.com/maps/api/geocode/json?address="+string
        json_string = requests.get(maps_url).content
        json_dict = json.loads(json_string)
        lat = json_dict['results'][0]['geometry']['location']['lat']
        lng = json_dict['results'][0]['geometry']['location']['lng']
        return HttpResponse(lat, lng) #It only prints lat, does not print lng
我的Html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>geog</title>
</head>
<body>
<form action="" method="POST"> {% csrf_token %}
    <input type="text" name='location'/>
    <button type="submit">submit</button>
</form>
</body>
</html>

geog
{%csrf_令牌%}
提交
可能是

# this will return a json object with a lat and lng property which have the desired values
return HttpResponse(json.dumps({"lat":lat, "lng":lng}), content_type="application/json")

创建一个包含两个值的字符串并放入
HttpResponse()
,或者将
render()
与另一个html文件一起使用,并将
lat,lng
作为参数(并且在html中使用
{lat lat}
{lng}
),如果我必须使用render,我必须创建一个新模板和新URL。字符串的想法听起来更好。在这种情况下,最好使用django.http.JsonResponse-