如何从 Django generic.ListView 中的用户前端获取参数?

我正在构建一个应用程序,用户可以在其中搜索附近的位置。为此,我在我的views.py:


latitude = 23.734413

longitude = 90.4082535


user_location = Point(longitude, latitude, srid=4326)

class NearbyServices(generic.ListView):

    model = Service

    context_object_name = 'services'

    queryset = Service.objects.annotate(distance=Distance('location', user_location)).order_by('distance')[0:6]

    template_name = 'services/nearby.html'

我目前正在使用硬编码的用户位置,但我想让用户通过首先使用 HTML5 GeoLocation API 获取他们的位置来找到附近的位置。任何有关如何将其位置从前端获取到 listview 功能的帮助都会非常有帮助!


千巷猫影
浏览 127回答 1
1回答

弑天下

与任何基于 Django 类的视图一样,如果您需要根据请求数据自定义任何内容,则需要在方法中进行。在这种情况下,您应该删除该queryset属性并定义get_queryset:class NearbyServices(generic.ListView):    model = Service    context_object_name = 'services'    template_name = 'services/nearby.html'    def get_queryset(self):        user_location = self.request.however_you_get_the_location        queryset = Service.objects.annotate(distance=Distance('location', user_location)).order_by('distance')[0:6]        return queryset
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python