Django - 将js变量传递给django视图 [英] Django - pass js variable to django view
问题描述
我的问题与Google Maps JavaScript API相关。更具体的自动完成功能。
My question is related to the Google Maps JavaScript API. More specific the autocomplete function.
我已经将自动完成功能添加到我的测试网站的搜索栏,这样可以正常工作,但现在我想通过所选择的参数到Django视图。在这里我被卡住了。
I've added the autocomplete function as a search bar to my test site and this works fine, but now I want to pass the chosen paramater to a Django view. And here I'm stuck.
这是我在我的模板中所拥有的:
This is what I have in my template:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
});
</script>
<form method="post" action="">{% csrf_token %}
<input id="searchTextField" type="text" placeholder="Enter a location" autocomplete="on">
<input type="submit" value="Search" class="postfix button"/>
</form>
这在我看来:
def homepage(request):
if request.method == 'POST':
location = request.POST
else:
location = ''
return render_to_response('homepage.html', {'location':location}, context_instance = RequestContext(request))
我想要做的是将变量'place'传递给我的Django视图中的变量'location'(var的位置应该包含lat和lon,这样我想使用进一步在Geodjango)。 request.POST
提供以下内容:< QueryDict:{u'csrfmiddlewaretoken':[u'4xp3nNwzeITb1zHhkBkSGlZSPtGwmuMB']}>
但是我不能使用。
What I want to do is to pass the variable 'place' to the variable 'location' in my Django view (the var place should contain the lat and lon, and this I want to use then further in Geodjango). The request.POST
gives the following: <QueryDict: {u'csrfmiddlewaretoken': [u'4xp3nNwzeITb1zHhkBkSGlZSPtGwmuMB']}>
But this I can't use.
是否可以将var place的内容传递给django视图?
Is it possible to pass the content of var place to the django view?
感谢您的反馈!
编辑:
我目前使用geopy的解决方法:
my workaround for the moment using geopy:
模板:
<input id="searchTextField" name="searchTextField" type="text" placeholder="Enter a location" autocomplete="on">
查看:
if request.method == 'POST':
location = request.POST.get('searchTextField')
gn = geocoders.Google()
place, (lat, lng) = gn.geocode(location)
仍然寻找一种访问 var place
在脚本
中。这是可能吗?
Still looking for a way to access the var place
in the script
. Is this possible?
推荐答案
首先在您的搜索中添加名称
输入。假设你像 id
一样调用 searchTextField
。那么你可以执行 request.POST.get('searchTextField')
。
First add a name
attribute to your search input. Let's say you called it searchTextField
like the id
. Then you can do request.POST.get('searchTextField')
.
这篇关于Django - 将js变量传递给django视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!