def test_filter_constituency_by_user(self):
        empty = models.filter_where_customuser_fewer_than(1)
        self.assertEqual(len(empty), 2)
        # add an inactive user.  Shouldn't make a difference
        self.users[2].constituencies.add(self.constituencies[0])
        empty = models.filter_where_customuser_fewer_than(1)
        
        self.assertEqual(len(empty), 2)
        
        self.users[1].constituencies.add(self.constituencies[0])
        empty = models.filter_where_customuser_fewer_than(1)
        self.assertEqual(len(empty), 1)

        more = models.filter_where_customuser_more_than(0)
        self.assertEqual(len(more), 1)
def constituencies_with_fewer_than_rss(request,
                                       volunteers=1):
    current_site = Site.objects.get_current()
    constituencies = models.filter_where_customuser_fewer_than(volunteers)
    context = {'constituencies': constituencies}
    context['site'] = current_site
    return render_with_context(request,
                              'geo.rss',
                              context,
                              mimetype="application/atom+xml")
Exemplo n.º 3
0
def _get_nearby_context(request):
    """Returns a context suitable for displaying and searching lists of
    nearby constituencies
    """
    my_constituencies = []
    if hasattr(request.user, 'ordered_constituencies'):
        my_constituencies = request.user.ordered_constituencies.all()
    context = {'my_constituencies': my_constituencies}
    context['constituencies'] = []
    tick_instructions = "Tick a box and scroll"
    if len(my_constituencies) > 0:
        try:
            const = my_constituencies[0]
            year = settings.CONSTITUENCY_YEAR
            all_const = Constituency.objects.filter(year=year)
            all_const = all_const.exclude(pk__in=my_constituencies)
            neighbours = const.neighbors(limit=5,
                                         constituency_set=all_const)
            missing = models.filter_where_customuser_fewer_than(1)
            missing_neighbours = const.neighbors(
                limit=5,
                constituency_set=missing)

            context["search_results"] = [
                (feedback("We found these constituencies near", const.name),
                 neighbours)]
            context["missing_search_results"] = [
                (feedback(("These are the nearest places where there "
                           "aren't any volunteers yet"), ""),
                 missing_neighbours)]
        except KeyError:
            # Any problems looking up neighbours means we pretend to
            # have none
            pass

    # searching for a constituency by postcode or placename
    if request.method == "GET":
        if request.GET.has_key("q"):
            place = request.GET["q"]
            if not place.strip():
                context['search_results'] = (
                    "Please enter a postcode or place name", [])
            else:
                context["search_results"] = place_search(place)
    return context
Exemplo n.º 4
0
def constituency(request, slug, year=None):
    context = _get_nearby_context(request)
    if request.GET.has_key('email'):
        # store in a session for things coming from TWFY that don't
        # require a login
        request.session['email'] = request.GET['email']
        request.session['postcode'] = request.GET.get('postcode', '')
        request.session['name'] = request.GET.get('name', '')
        context['came_from_ynmp'] = True
    if year:
        year = "%s-01-01" % year
    else:
        year = settings.CONSTITUENCY_YEAR

    try:
        constituency = Constituency.objects.all()\
                       .filter(slug=slug, year=year).get()
        context['constituency'] = constituency
        context = _add_candidacy_data(context, constituency)
    except Constituency.DoesNotExist:
        raise Http404
    
    if request.method == "POST" and 'notifypost' in request.POST:
        try:
            notify_object = NotifyComment.objects.get(user=request.user,
                                                      constituency=constituency)
        except NotifyComment.DoesNotExist:
            notify_object = NotifyComment.objects.create(user=request.user,
                                                         constituency=constituency,
                                                         notify_type=NotifyComment.Types.none)

        if 'notify' in request.POST:
            notify_object.notify_type = NotifyComment.Types.every
        else:
            notify_object.notify_type = NotifyComment.Types.none

        notify_object.save()

        return HttpResponseRedirect(reverse('constituency', args=[slug]))
    
    elif request.method == "POST" and 'subject' in request.POST:
        within_km = int(request.POST['within_km'])

        nearest = None
        if within_km == -1:
            nearest = Constituency.objects.all()
        else:
            nearest = constituency.neighbors(limit=100,
                                             within_km=within_km)
            nearest = nearest + [constituency]
        context['nearest'] = nearest
        context['subject'] = request.POST['subject']
        context['message'] = request.POST['message']
        context['within_km'] = within_km
        couldnt_send = []
        sent = []
        if request.POST.get('go', ''):
            count = 0
            site = Site.objects.get_current()
            for c in nearest:
                for user in c.customuser_set.filter(is_active=True):
                    if user in sent: # send once
                        continue
                    try:
                        profile = user.registrationprofile_set.get()
                        footer = render_to_string('email_unsub_footer.txt',
                                                  {'site':site,
                                                   'user_profile':profile})
                        message = "%s\n\n%s" % (request.POST['message'],
                                                footer)
                        send_mail(request.POST['subject'],
                                  message,
                                  settings.DEFAULT_FROM_EMAIL,
                                  [user.email,])
                        count += 1
                        sent.append(user)
                    except RegistrationProfile.DoesNotExist:
                        couldnt_send.append(user)
            context['recipients'] = count
            context['error_recipients'] = couldnt_send
        return render_with_context(request,
                                   'constituency_email.html',
                                   context)
    else:
        latspan = lonspan = 1
        missing = models.filter_where_customuser_fewer_than(1)
        missing_neighbours = constituency.neighbors(
            limit=5,
            constituency_set=missing)
        if missing_neighbours:
            furthest = missing_neighbours[-1]

            if None not in (furthest.lat, furthest.lon,
                            constituency.lat, constituency.lon):
                # not in Northern Ireland
                latspan = abs(furthest.lat - constituency.lat) * 2
                lonspan = abs(furthest.lon - constituency.lon) * 2
        context['latspan'] = latspan
        context['lonspan'] = lonspan
        context['activity'] = generate_activity([constituency],
                                                show_constituency=False)
  
        if request.user.is_authenticated():
            context['volunteer_here'] = \
                 bool(request.user.constituencies\
                      .filter(id=constituency.id))
        else:
            context['volunteer_here'] = False

        context['is_constituency_page'] = True
        context['notify_object'] = None
        if request.user.is_authenticated():
            try:
                context['notify_object'] = \
                     NotifyComment.objects.get(user=request.user,
                                               constituency=constituency)
            except NotifyComment.DoesNotExist:
                pass
        
        return render_with_context(request,
                                   'constituency.html',
                                   context)