Ejemplo n.º 1
0
def set_location(request):
    """
    Logged in users use this view to set the location on their profile -
    anonymous users get a cookie instead
    """
    from zoo.search import search_locations
    (current_location, (lat, lon)) = location_from_request(request)

    location = request.POST.get('location', '')
    msg = ''

    if location:
        description, (lat, lon) = google_geocode(location)
        if description is not None:
            msg = 'Your location has been set to <strong>%s</strong>.' % description
            try:
                random_animal = Species.objects.order_by('?')[0]
                nearest = nearest_places_with_species(random_animal.common_name, (lat, lon))
                msg += ' As an example, your nearest <a href="%s">%s</a> is %s miles away, at <a href="%s">%s</a>.' % (random_animal.urls.absolute, random_animal.common_name, int(nearest[0].distance_miles+0.5), nearest[0].urls.absolute, nearest[0])
            except IndexError:
                nearest = None
            current_location = description
            # Set their location
            if not request.user.is_anonymous():
                profile = request.user.get_profile()
                profile.location = description
                profile.latitude = lat
                profile.longitude = lon
                profile.recalculate_percentage_complete()
                profile.save()
            else:
                # Set it in a cookie instead
                response = Redirect('/set-location/?done')
                response.set_cookie(
                    key = 'location',
                    value = '%s:%f,%f' % tuple(
                        [description] + result['latlon']
                    ),
                    path = '/',
                )
                return response
        else:
            msg = 'No matches for your search'
    return render(request, 'accounts/set_location.html', {
        'msg': msg,
        'current_location': current_location,
    })
Ejemplo n.º 2
0
def species(request, slug):
    try:
        species = Species.objects.get(slug=slug)
    except Species.DoesNotExist:
        # eggs
        species = get_object_or_404(SuperSpecies, slug=slug)
        t = loader.get_template('animals/%s.html' % species.type)
        c = Context({'species': species})
        return HttpResponse(t.render(c), status=species.status)
    
    num_favourites = species.favourited.count()
    
    # If we have the user's location, find the nearest animal of this species
    description, (latitude, longitude) = location_from_request(request)
    nearest = None
    if description:
        try:
            nearest = [p for p in nearest_places_with_species(
                'exactspecies:species_%s' % species.pk,
                '%f %f' % (latitude, longitude)
            ) if not p.is_unlisted][0]
        except IndexError:
            nearest = None
    
    spotters = User.objects.filter(
        created_sighting_set__species = species
    ).distinct()
    return render(request, 'animals/species.html', {
        'species': species,
        'favourited': species.is_favourited_by(request.user),
        'num_favourites': num_favourites,
        'nearest': nearest,
        'location_description': description,
        'spotters': spotters[0:SPOTTERS_ON_SPECIES_PAGE],
        'more_spotters': spotters.count() > SPOTTERS_ON_SPECIES_PAGE,
    })
Ejemplo n.º 3
0
def search_split(request, what, near):
    if near.lower() == 'me':
        (current_location, (lat, lon)) = location_from_request(request)
        if current_location:
            near = current_location
    # Look up location using Google geocoder (more likely to return results)
    name, (lat, lon) = google_geocode(near)
    if not name:
        # Treat as a lat/long pair instead, see if that works
        c = Client(settings.XAPIAN_BASE_URL, settings.XAPIAN_PERSONAL_PREFIX)
        result = c.parse_latlong(near)
        if result['ok']:
            lat, lon = result['latitude'], result['longitude']
        else:
            return search_single(
                request, '%s near %s' % (what, near), bypass=True
            )
    
    results, results_info, results_corrected_q = search_places(
        what or SEARCH_ALL, details=True, latlon=(lat, lon), num=PER_PAGE
    )
    species_results, species_results_info, species_results_corrected_q = \
        search_known_species(
            what, details=True, default_op=Query.OP_OR,
    )
    users_results, users_results_info, users_results_corrected_q = \
        search_users(
            what, details=True, default_op=Query.OP_OR,
    )
    
    results = [
        place for place in results if not place.is_unlisted
    ]
    
    for result in results:
        result.species_list = result.get_species()
        for species in result.species_list:
            if species in species_results:
                species.matches_search = True
        # If we got back a distance, bung that on there too
        try:
            result.distance = ([
                d for d in results_info['items'] 
                if d['id'] == 'places.Place:%s' % result.id
            ][0]['geo_distance']['latlon'] / 1609.344)
        except (KeyError, IndexError):
            pass
    
    return render(request, 'search/search_split.html', {
        'what': what,
        'near': near,
        'location_name': name,
        'results': results,
        'results_info': pformat(results_info),
        'results_corrected_q': results_corrected_q,
        'species_results': (species_results or [])[:5],
        'species_results_info': pformat(species_results_info),
        'species_results_corrected_q': species_results_corrected_q,
        'species_results_more': len(species_results or [])>5,
        'users_results': users_results,
        'users_results_info': pformat(users_results_info),
        'users_results_corrected_q': users_results_corrected_q,
    })
Ejemplo n.º 4
0
def homepage(request):

    reg_form = RegistrationForm()

    recent_sightings = Sighting.objects.order_by('-created_at')
    recent_sightings_favourites = None
    if request.user.is_authenticated():
        favourite_animals = Species.objects.filter(favourited=request.user)
        recent_sightings_favourites = Sighting.objects.filter(
            species__in=favourite_animals
        ).order_by('-created_at')

    featured = {}

    # Doing it this way means the page survives with 0 or >1 featured
    # sites.
    places = Place.objects.filter(featured=True).order_by('?')
    featured['place'] = places.count() > 0 and places[0] or None

    species = Species.objects.filter(featured=True).order_by('?')
    featured['species'] = species.count() > 0 and species[0] or None

    profiles = Profile.objects.filter(featured=True).order_by('?')
    featured['profile'] = profiles.count() > 0 and profiles[0] or None

    num_of_places = Place.objects.count()
    num_of_countries = Country.objects.filter(
        place__isnull = False
    ).distinct().count()

    if featured['place']:
        # Have to do this as django template method calls can't take params.
        try:
            featured['place'].species = featured['place'].get_species(
                limit=10
            )
        except Species.DoesNotExist:
            featured['place'].species = None

    if featured['species']:
        location, (lat, lon) = location_from_request(request)
        if (lat, lon) != (None, None):
            from zoo.search import nearest_places_with_species as npws
            nearest_species = npws(
                featured['species'].common_name, (lat, lon)
            )
            if nearest_species:
                featured['species'].nearest = nearest_species[0]
    
    if settings.SEARCH_ENABLED:
        default_search = ''
    else:
        default_search = 'SEARCH CURRENTLY DISABLED'
    
    return render(request, 'homepage.html', {
        'featured': featured,
        'num_of_places': num_of_places,
        'num_of_countries': num_of_countries,
        'reg_form': reg_form,
        'recent_sightings': recent_sightings,
        'recent_sightings_favourites': recent_sightings_favourites,
        'default_search': default_search,
        'recent_photos': recent_photos_for_homepage(),
        'recent_trips': recent_trips_for_homepage(5),
        'blog_posts': Post.objects.published().only(
            'publish', 'slug', 'title'
        ),
#        'recent_trips': Trip.objects.filter(
#            start__isnull=False
#        ).order_by('-start')[:5]
    })