Django Search using Ajax Requests

Ritwick Raj
AnitaB.org Open Source
2 min readJul 13, 2020

Moving on to Week 4 of GSoC’20, once again I had to work again on revamping the Search Feature on the portal, which helped searching for meetups on the Portal.

The problem with the previous search page seemed to have too many filters and sorts. My task was to make it simple. So i broke down the issue to the following steps.

Changing views.py

The view for the search already existed but the problem was that some of the features did not exist anymore because of the revamping of the Meetups after removing the Meetup Location about which I have spoken here.

So it basically involved changing a few fields which were being Posted by the Ajax Request.

class SearchView(ListView):
model = Meetup
template_name = "list_meetup.html"
@csrf_exempt
def post(self, request):
....
return JsonResponse({'search_results': results}, safe=False)

Above is the overview of the Code. Just by changing a few fields, we achieved the backend side of the search.

The Javascript Part

$.ajax({
type: "POST",
url: "search/",
data: Data,
success(a){ //inject data to the html div }

So after submitting the data from the client side to the view , the query is made using the django queryset and the result is returned to the success function.

Selecting User Location Using GeoIP2

GeoIP2 Database by Maxmind helps in getting the user location based on the IP Address Present in the the Request Header

For that we will be using Django IPWare which helps fetch the IP Address from the Header

Fetching the MaxMind Database for the City

g = GeoIP2()
lat, long = g.lat_lon(get_client_ip(request))

After this Step, GeoDjango is used to calculate the distance between the two Points and Sort by Distance, which povides the nearest meetups to the user.

geolocator = Nominatim(timeout=6)
meetup_loc = (geolocator.geocode(meetup.meetup_location))
user_point = Point((float)(long),
(float)(lat))
meetup_point = Point((float)(meetup_loc.raw['lon']),
(float)(meetup_loc.raw['lat']))
distance = (int)(user_point.distance(meetup_point)) * 100
results.sort(key=operator.itemgetter('distance'))

After all this Hustle, we get the final product which looks something like this

--

--