Saturday 31 October 2020

Django & Geopy : calcul distance btwn fixed position (post) and moving position (user.userprofile) position

I am looking for how to define a distance between two points. The first one is related to the post itself and does not change. It indicates the position of the post. The second would be linked to the user's position.

The problem is that nothing is displayed. Do you have an idea?

Thanks a lot for your help,


FIRST TRY :

user/models.py

    class UserProfile(models.Model):
        ...
        latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')
        longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')
post/models.py

class Cuisine(models.Model):
     ...
     latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')
     longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0')

     def distance_post(self, request):
        post_situation = (self.longitude, self.latitude)
        user_situation = (self.request.user.userprofile.longitude, self.request.user.userprofile.latitude)
        
        return geodesic(post_situation, user_situation).km

SECOND TRY:

@register.inclusion_tag('index.html')
def distance_post(request):
    post_situation = (request.GET['longitude'], request.GET['latitude'])
    user_situation = (self.request.user.userprofile.longitude, self.request.user.userprofile.latitude)
    distance = geodesic(post_situation, user_situation).km
    
    return {'distance': distance}  

But nothing works, do you have any idea?

Here is where I'd like to to use distance

post/views.py :

def Homemainpage(request):
    post = Cuisine.objects.filter(status=0).order_by('-publishing_date').all()
    
    paginator = Paginator(post, 3)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    listaliments = ListAliments.objects.filter(status=1).all()
    typerepas = Typerepas.objects.filter(status=1).all()
    sperepas = Sperepas.objects.filter(status=1).all()
    
    return render(request, 'index.html', {
        'post': post,
        'listaliments': listaliments,
        'typerepas': typerepas,
        'sperepas': sperepas,
        'page_obj': page_obj,
    })

Another idea will be to create something like a pattern to use in a template:

And to load directly the longitude and latitude into template for calculation. Does anyone has an idea about that?



from Django & Geopy : calcul distance btwn fixed position (post) and moving position (user.userprofile) position

No comments:

Post a Comment