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

时间:2016-11-01 00:53:00

标签: python json django http

好的,我对django很新,我正在构建一个非常简单的应用程序。用户将位置输入文本框,我从谷歌地图获取该位置的坐标并在下一页打印。到目前为止,我已经能够获得JSON文件中的坐标以及许多其他信息。我也成功地隔离了纬度和经度,并将它们存储在单独的变量中。我不能让它们打印出来。只打印一个值。有人可以帮我吗?这是我到目前为止所写的: 我的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>

1 个答案:

答案 0 :(得分:0)

它将是

# 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")