如何通过ID渲染Django的位置字段?

时间:2019-12-04 11:31:34

标签: javascript django leaflet geojson geodjango

我在Django中有一个像这样的模型:

...

class Post (models.Model)

 title = models.CharField(max_length=120)

 location = models.PointField(srid=4326, null=True, blank=True)
 objects = GeoManager()

 def __unicode__(self):
    return self.title

 def get_absoulute_url(self):
     return reverse("post_map", kwargs={
    'id':self.id

    })
...

我想通过id渲染位置地点:

...

path('post-map/<id>/post_map/',post_map,name='post_map')
path('post-map/<id>/post_page/',post_page,name='post_map')
path('post-map/<id>/home_page/',home_page,name='post_map')
...

一个view.py:

...

def post_map(request,id):
     #i can render Post.objects.all() but i cant render this:
     name = serialize('geojson',get_objects_or_404(Post, id=id)
     return HttpResponse(name,content_type='json')


def home_page(request):
    return render(request,'home_page.html')


def post_page(request,id):

    post = get_object_or_404(Post, id=id)

    context = {
       'post':post,
    }
    return render(request,'post-pagepltest.html',context)
...

这是post_page.html

中代码的一部分
<div class="w-100 map border ">

<i class="fas fa-map-marker-alt  float-right"></i>
<a href="{{ post.get_absolute_url }}home_page">
<span class="badge badge-pill float-left mr-auto badge-danger "> map- 
 location </span>
</a>
</div>

和home_page.html是:

...

<!DOCTYPE html>
<html>
{% load static %}
{% load leaflet_tags %}

<head>
    {% leaflet_js %}
    {% leaflet_css %}
    <title> home </title>


    <style type="text/css">
      #gis {width:80%; height:700px;}
    </style>

    <script type ="text/javascript" src="{% static 'js2/leaflet.ajax.js' %}" ></script>




</head>
<body>
<h3>we are heroes!!<h3>
<br>

<script type="text/javascript">


  function our_layers(map,options){
    var datasets = new L.GeoJSON.AJAX("{% url 'post_map' %}",{

    });
    datasets.addTo(map);
  }



</script>
{% leaflet_map "gis" callback="window.our_layers" %}
</body>
</html>

但是我不能通过id渲染它,有什么办法可以解决这个问题? 我可以保存数据,也可以渲染所有位置以查看地图功能   名称=序列化('geojson',get_objects_or_404(Post,id = id) 但我无法通过每个帖子的每个ID呈现 我如何按id渲染帖子以显示特定的位置?

name = serialize('geojson',get_objects_or_404(Post,id = id)

1 个答案:

答案 0 :(得分:1)

您的网址需要id参数,因此您应该这样做;

{% url 'post_map' id=1 %}

您可以使用它来获取ID。


此外,您的视图还应将上下文传递给呈现的模板:

from django.shortcuts import render

def map (request,id):
 name = serialize('geojson',get_objects_or_404(Post, id=id)
 # you can call {{name}}
 return render(request, "home_page.html", {'name':name})