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

How to get parameter from user front-end in 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 获取他们的位置,从而找到附近的位置。任何有关如何从前端将它们的位置获取到列表视图函数的帮助都将非常有帮助!

与任何基于 Django class 的视图一样,如果您需要根据请求数据自定义任何内容,您需要在方法中进行。在这种情况下,您应该删除 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