Beispiel #1
0
def quantity_for_last_harvest(request, pk=None, year=None):
    garden = pk
    gardener = request.GET.get('gardener', None)
    crop = request.GET.get('crop', None)

    result = {
        'plants': '',
        'area': '',
    }
    if garden and gardener and crop:
        garden = get_object_or_404(Garden, pk=garden)
        if not request.user.has_perm('can_edit_any_garden'):
            profile = get_profile(request.user)
            if garden not in profile.gardens.all():
                return HttpResponseForbidden()
        try:
            harvest = Harvest.objects.filter(
                gardener__garden=garden,
                gardener__pk=gardener,
                crop__pk=crop
            ).order_by('-recorded')[0]
        except IndexError:
            raise Http404

        result['plants'] = harvest.plants
        try:
            result['area'] = float(harvest.area)
        except:
            result['area'] = None
    return HttpResponse(json.dumps(result), content_type='application/json')
 def get_gardens(self, user):
     try:
         if user.is_authenticated():
             profile = get_profile(user)
             return profile.gardens.all().order_by('name')
     except Exception:
         return []
Beispiel #3
0
 def remove_garden_from_user(self, garden):
     user = self.request.user
     if user and user.is_authenticated():
         GardenMembership.objects.filter(
             garden=garden,
             user_profile=get_profile(user)
         ).delete()
Beispiel #4
0
 def get_gardens(self, user):
     try:
         if user.is_authenticated():
             profile = get_profile(user)
             return profile.gardens.all().order_by('name')
     except Exception:
         return []
Beispiel #5
0
 def get_object(self, queryset=None):
     object = super(GardenMixin, self).get_object(queryset=queryset)
     if self.request.user.has_perm('farmingconcrete.can_edit_any_garden'):
         return object
     elif object in get_profile(self.request.user).gardens.all():
         return object
     raise PermissionDenied
Beispiel #6
0
 def get_object(self, queryset=None):
     object = super(GardenMixin, self).get_object(queryset=queryset)
     if self.request.user.has_perm('farmingconcrete.can_edit_any_garden'):
         return object
     elif object in get_profile(self.request.user).gardens.all():
         return object
     raise PermissionDenied
Beispiel #7
0
 def get_user_gardens(self):
     user = self.request.user
     try:
         if user.is_authenticated():
             profile = get_profile(user)
             return profile.gardens.all().order_by('name')
     except Exception:
         return []
Beispiel #8
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        if not 'queryset' in kwargs:
            kwargs['queryset'] = GardenType.objects.all()
        super(GardenTypeField, self).__init__(*args, **kwargs)

        if user and not user.has_perm('can_edit_any_garden'):
            profile = get_profile(user)
            if profile.garden_types.count() > 0:
                self.queryset = self.queryset & profile.garden_types.all()
Beispiel #9
0
    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        if not 'queryset' in kwargs:
            kwargs['queryset'] = GardenType.objects.all()
        super(GardenTypeField, self).__init__(*args, **kwargs)

        if user and not user.has_perm('can_edit_any_garden'):
            profile = get_profile(user)
            if profile.garden_types.count() > 0:
                self.queryset = self.queryset & profile.garden_types.all()
def garden_types(request):
    """
    Context processor that provides the GardenTypes available for the given user.
    """
    user = request.user

    if user and user.is_authenticated():
        profile = get_profile(user)
        types = GardenType.objects.all()
        if profile.garden_types.all().count() > 0:
            types = types & profile.garden_types.all()
        return {"garden_types": types}
    return {}
def garden_types(request):
    """
    Context processor that provides the GardenTypes available for the given user.
    """
    user = request.user

    if user and user.is_authenticated():
        profile = get_profile(user)
        types = GardenType.objects.all()
        if profile.garden_types.all().count() > 0:
            types = types & profile.garden_types.all()
        return {'garden_types': types}
    return {}
Beispiel #12
0
    def add_admin(self, user):
        """Add the given user as an admin of this group."""
        from accounts.models import GardenGroupUserMembership
        from accounts.utils import get_profile

        membership, created = GardenGroupUserMembership.objects.get_or_create(
            group=self,
            user_profile=get_profile(user),
            defaults={ 'added_by': user, 'is_admin': True },
        )
        if not created:
            membership.is_admin = True
        membership.save()
        return membership
Beispiel #13
0
def garden_feature(garden, user=None):
    """Get a geojson Feature for a garden"""
    is_user_garden = (user and user.is_authenticated() and
                      get_profile(user).gardens.filter(pk=garden.pk).exists())

    # Round coordinates if user doesn't have access to them
    coordinates = (float(garden.longitude), float(garden.latitude))
    if not (garden.share_location or is_user_garden):
        coordinates = [round(coord, 2) for coord in coordinates]

    # Only show name if user has access to it
    properties = {}
    if garden.share_name or is_user_garden:
        properties['name'] = garden.name
    return geojson.Feature(garden.id,
                           geometry=geojson.Point(coordinates=coordinates),
                           properties=properties)
Beispiel #14
0
    def add_admin(self, user):
        """Add the given user as an admin of this group."""
        from accounts.models import GardenGroupUserMembership
        from accounts.utils import get_profile

        membership, created = GardenGroupUserMembership.objects.get_or_create(
            group=self,
            user_profile=get_profile(user),
            defaults={
                'added_by': user,
                'is_admin': True
            },
        )
        if not created:
            membership.is_admin = True
        membership.save()
        return membership
Beispiel #15
0
def garden_feature(garden, user=None):
    """Get a geojson Feature for a garden"""
    is_user_garden = (user and user.is_authenticated() and 
                      get_profile(user).gardens.filter(pk=garden.pk).exists())

    # Round coordinates if user doesn't have access to them
    coordinates = (float(garden.longitude), float(garden.latitude))
    if not (garden.share_location or is_user_garden):
        coordinates = [round(coord, 2) for coord in coordinates]

    # Only show name if user has access to it
    properties = {}
    if garden.share_name or is_user_garden:
        properties['name'] = garden.name
    return geojson.Feature(
        garden.id,
        geometry=geojson.Point(coordinates=coordinates),
        properties=properties
    )
Beispiel #16
0
    def add_garden_to_user(self, garden):
        user = self.request.user
        if not (user and user.is_authenticated()):
            return

        # Make sure user isn't already in garden
        existing_membership = GardenMembership.objects.filter(
            garden=garden,
            user_profile__user=user
        )
        if existing_membership.exists():
            return

        # Make user the admin if they're the first
        is_first = not GardenMembership.objects.filter(garden=garden).exists()
        garden_membership = GardenMembership(
            garden=garden,
            user_profile=get_profile(user),
            is_admin=is_first,
            added_by=user,
        )
        garden_membership.save()
Beispiel #17
0
 def can_edit_garden(self, user, record):
     if user.has_perm('farmingconcrete.can_edit_any_garden'):
         return True
     return get_profile(user).gardens.filter(
         pk=record.garden.pk).count() > 0
Beispiel #18
0
 def get_user_gardens(self):
     profile = get_profile(self.request.user)
     return profile.gardens.all()
Beispiel #19
0
def gardens_geojson(request):
    """Get GeoJSON for requested gardens"""

    gardens = Garden.objects.exclude(latitude=None, longitude=None)

    ids = request.GET.get('ids', None)
    cropcount = request.GET.get('cropcount', None)
    gardenid = request.GET.get('gardenid', None)
    group = request.GET.get('group', None)
    harvestcount = request.GET.get('harvestcount', None)
    metric = request.GET.get('metric', None)
    participating = request.GET.get('participating', None)
    records = request.GET.get('records', None)
    types = request.GET.get('gardentype', None)
    borough = request.GET.get('borough', None)
    year = request.GET.get('year', datetime.now().year)
    user_gardens = request.GET.get('user_gardens', False)

    if metric:
        records = registry[metric]['model'].objects.for_year(year)
        ids = records.values_list('garden__pk', flat=True)

    if user_gardens:
        user = request.user
        try:
            if user.is_authenticated():
                profile = get_profile(user)
                ids = profile.gardens.all().values_list('pk', flat=True)
        except Exception:
            pass

    if gardenid:
        ids = [gardenid,]

    if ids:
        try:
            ids = ids.split(',')
        except Exception:
            pass
        gardens = gardens.filter(id__in=ids)
    if types and types != 'all':
        types = types.split(',')
        gardens = gardens.filter(type__short_name__in=types)
    if borough:
        gardens = gardens.filter(borough=borough)
    if group:
        try:
            gardengroup = GardenGroup.objects.get(pk=group)
            gardens = gardens.filter(
                pk__in=gardengroup.active_gardens().values_list('pk', flat=True)
            )
        except GardenGroup.DoesNotExist:
            pass

    if cropcount and cropcount != 'no':
        gardens = gardens.filter(box__patch__added__year=year)
    elif harvestcount and harvestcount != 'no':
        gardens = gardens.filter(gardener__harvest__harvested__year=year)
    elif participating and participating != 'no':
        gardens = gardens.filter(Q(box__patch__added__year=year) |
                                 Q(gardener__harvest__harvested__year=year))
    elif records and records != 'no':
        gardens = gardens.filter(has_metric_records=True)

    gardens = gardens.distinct()
    return HttpResponse(geojson.dumps(garden_collection(gardens, user=request.user)),
                        content_type='application/json')
Beispiel #20
0
 def can_edit_garden(self, user, record):
     if user.has_perm('farmingconcrete.can_edit_any_garden'):
         return True
     return get_profile(user).gardens.filter(pk=record.garden.pk).count() > 0
Beispiel #21
0
 def get_user_gardens(self):
     profile = get_profile(self.request.user)
     return profile.gardens.all()