Пример #1
0
def edit_user(request, id):
    id = int(id)
    if request.user.id != id and not request.user.has_perm("signup.edit_customuser"):
        return HttpResponse(status=403)
    else:    
        data = None
        user = CustomUser.objects.get(pk=id)
        
        if request.method == "POST":
            data = request.POST
        else:
            data = user.__dict__

        form = EditUserForm(user, data)

        notice = ""

        if request.method == "POST":
            if form.is_valid():
                user = form.save()
                notice = "User profile saved"
        
        context = {'form': form, 'edit_user': user, 'notice': notice,}

        return render_with_context(request, "user_edit.html", context)
Пример #2
0
def chart(request):
    context = {}
    context['invites'] = SurveyInvite.objects.all()
    invites_sent = aggregates.Count(
        'candidate__candidacy__surveyinvite__emailed',
        equals=True)
    invites_sent.name = 'CountIf'
    replies_received = aggregates.Count(
        'candidate__candidacy__surveyinvite__filled_in',
        equals=True)
    replies_received.name = 'CountIf'
    parties = Party.objects.all()\
              .filter(candidate__candidacy__surveyinvite__emailed=True)\
              .annotate(invites_sent=invites_sent)\
              .distinct()\
              .order_by('-invites_sent')
    for party in parties:
        party.replies_received = SurveyInvite.objects\
                                 .filter(filled_in=True,
                                         candidacy__candidate__party=party)\
                                         .count()

    parties = list(parties[:15])
    parties.sort(lambda x, y: cmp(float(y.replies_received)/y.invites_sent,
                                  float(x.replies_received)/x.invites_sent))
    context['parties'] = parties
    return render_with_context(request,
                               'chart.html',
                               context)
Пример #3
0
def constituencies(request):
    year = settings.CONSTITUENCY_YEAR
    context = {}
    constituencies = Constituency.objects.all()\
                     .filter(year=year)\
                     .order_by('name')
    context['constituencies'] = _constituency_decorator(
        constituencies)
    return render_with_context(request,
                               'constituencies.html',
                               context)
Пример #4
0
def user(request, id):
    from tasks.models import TaskUser # Import here to avoid circular dependency
    
    context = {}
    user = get_object_or_404(CustomUser, pk=id)
    context['profile_user'] = user
    context['activity'] = TaskUser.objects.\
        filter(user=user).\
        filter(user__can_cc=True).\
        filter(state__in=[TaskUser.States.started,TaskUser.States.completed]).\
        order_by('-date_modified').distinct()
    context['badges'] = user.badge_set.order_by('-date_awarded')
    return render_with_context(request,
                               'user.html',
                               context)
Пример #5
0
def all_users(request, slug=None):
    context = {}
    constituency = get_object_or_404(Constituency, slug=slug)
    users = constituency.customuser_set.all()
    context['users'] = users
    context['constituency'] = constituency
    if request.user.is_authenticated():
        context['show_email'] = \
            bool(request.user.constituencies\
                 .filter(id=constituency.id))
    else:
        context['show_email'] = False

    return render_with_context(request,
                               'all_users.html',
                               context)
Пример #6
0
def home2(request):
    context = _get_statistics_context()
    if request.user.is_anonymous():
        if request.method == "POST":
            form = UserForm(request.POST, request.FILES)
            if form.is_valid():
                profile = form.save()
                user = authenticate(username=profile.user.email)
                login(request, user)
                return HttpResponseRedirect(reverse('welcome'))
            else:
                context['form'] = form
        else:
            context['form'] = UserForm()
        return render_with_context(request,
                               'home_2.html',
                               context)
    else:
        return HttpResponseRedirect(reverse('welcome'))
Пример #7
0
def email_reminder(request):
    messages = []
    if request.method == "POST":
        email = request.POST['email']
        
        user = None
        try:
            user = CustomUser.objects.get(email=email)
        except CustomUser.DoesNotExist:
            messages.append("I couldn't find a user with email address %s" % email)
        else:
            # we assume that if they previously unsubscribed, they've
            # now changed their minds
            user.unsubscribed = False
            user.save()
            profile = user.registrationprofile_set.get()
            profile.send_activation_email()
            messages.append("Activation email re-sent. Please check your %s inbox. If it isn't there, check your spam folders" % email)
    context = {'messages':messages}
    return render_with_context(request,
                               "email_reminder.html",
                               context) 
Пример #8
0
def add_constituency(request):
    context = _get_nearby_context(request)
    # adding another constituency
    if request.method == "POST":
        if request.POST.has_key('add') and request.POST.has_key('add_c'):
            add_c = request.POST.getlist('add_c')
            if type(add_c) != types.ListType:
                add_c = [add_c]
            constituencies = Constituency.objects.all()\
                             .filter(slug__in=add_c)
            mine = context['my_constituencies']
            constituencies = constituencies.exclude(pk__in=mine)
            request.user.constituencies.add(*constituencies.all())
            request.user.save()
            sig = signals.user_join_constituency
            sig.send(None,
                     user=request.user)
            return HttpResponseRedirect("/add_constituency/")

    return render_with_context(request,
                               'add_constituency.html',
                               context)
Пример #9
0
def table(request):
    context = {}
    context['full_table'] = _build_board(with_user_ob=True)
    return render_with_context(request,
                               'table.html',
                               context)
Пример #10
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)
Пример #11
0
def parties(request):
    context = {}
    statements = []
    #for party in Party.objects.all():
    #    data = {}
    #    statements =
    #    Statement.objects.filter(national=True).annotate(agreement=Avg('surveyresponse__agreement'))
    chart = ""
    for statement in Statement.objects.filter(national=True):
        bottoms = []
        boxbottoms = []
        boxtops = []
        tops = []
        parties = Party.objects.annotate(count=Count('candidate'))\
                  .filter(count__gt=200)
        something = False
        for party in parties:
            responses = SurveyResponse.objects\
                        .filter(candidacy__candidate__party=party,
                                statement=statement)
            avg = responses.aggregate(avg=Avg('agreement'))['avg']
            stddev = responses.aggregate(stddev=StdDev('agreement'))['stddev']
            if responses.count():
                error = stddev/math.sqrt(responses.count()-1)
            else:
                error = None
            if error:
                something = True
                bottoms.append(str(int(avg - stddev)))
                boxbottoms.append(str(int(avg - 1)))
                boxtops.append(str(int(avg + 1)))
                tops.append(str(int(avg + stddev)))            
                party.avg = avg
                party.stddev = stddev
                party.error = error
            else:
                bottoms.append("")
                boxbottoms.append("")
                boxtops.append("")
                tops.append("")
                party.avg = ""
                party.stddev = ""
                party.error = ""
        chart = "http://chart.apis.google.com/chart?chs=800x125&cht=lc&chd=t0:"
        chart += ",".join(bottoms)
        chart += "|"
        chart += ",".join(boxbottoms)
        chart += "|"
        chart += ",".join(boxtops)
        chart += "|"
        chart += ",".join(tops)
        chart += "&chm=F,0000FF,0,,20&chxt=x,y&chxl=0:|"
        chart += "|".join([urllib.quote_plus("".join([y[0] for y in x.name.split(" ")])) for x in parties])
        if something:
            statements.append({'parties':parties,
                               'statement':statement,
                               'chart':chart})
        
    context['statements'] = statements
    context['chart'] = chart
    return render_with_context(request,
                               'parties.html',
                               context)
Пример #12
0
def pester(request, constituency):
    if not request.user.is_superuser:
        # turned off once election has started
        return HttpResponseRedirect(
            reverse('home'))

    context = {}
    constituency = Constituency.objects.get(pk=constituency)
    context['constituency'] = constituency
    count = SurveyInvite.objects.filter(filled_in=True).count()
    context['total_count'] = count
    context = _add_candidacy_data(context, constituency)
    if context['contacted'].count() == 1:
        context['one_left'] = True
        if context['contacted'][0].candidate.party.name == "Conservative Party":
            context['one_tory_left'] = True            
    if request.GET.has_key('pester'):
        email_candidacies = []
        no_email_candidacies = []
        key = 'candidacy_'
        for k, v in request.GET.items():
            if k.startswith(key):
                candidacy = Candidacy.objects.get(
                    pk=k[len(key):],
                    ynmp_constituency__constituency=constituency)
                if candidacy.candidate.email:
                    email_candidacies.append(candidacy)
                else:
                    no_email_candidacies.append(candidacy)
        context['email_candidacies'] = email_candidacies
        context['no_email_candidacies'] = no_email_candidacies
    default_msg = "Dear candidates,\n\n\n\n\nYours,\n%s\n%s"
    if request.user.is_anonymous():
        user_email = request.session.get('email', '')
        user_name = request.session.get('name', '')
        user_postcode = request.session.get('postcode', '')
    else:
        user_email = request.user.email
        user_name = "%s %s" % (request.user.first_name,
                               request.user.last_name)
        user_postcode = request.user.postcode
    default_msg = default_msg % (user_name, user_postcode)
    context['message'] = default_msg
    context['user_email'] = user_email
    if request.method == "POST":
        if request.POST.has_key('finished'):
            return render_with_context(request,
                                       'pester_thanks.html',
                                       context)            
        candidacies = []
        for key in request.POST.getlist('candidacy'):
            candidacy = Candidacy.objects.get(
                pk=int(key),
                ynmp_constituency__constituency=constituency)
            candidacies.append(candidacy)
        subject = request.POST.get('subject','').strip()
        message = request.POST['message'].strip()
        mfrom = request.POST.get('mfrom','').strip()
        debug_to = request.POST.get('debug_to','').strip()
        if not subject:
            context['subject'] = subject
            context['message'] = message
            context['mfrom'] = mfrom
            context['error'] = "You must give the email a subject"
        else:

            if not user_email:
                user_email = request.POST.get('mfrom', 'unknown')
            sbj = "[ NONE ]"
            msg = ""
            for candidacy in candidacies:
                # calculate the login link
                quiz_url = "http://election.theyworkforyou.com/survey/"
                token = candidacy.surveyinvite_set.get().survey_token
                quiz_url += token
                quiz_words = "To start the survey, please visit %s" % quiz_url
                msg = ("This is a message from a voter in your "
                       "constituency about the TheyWorkForYou "
                       "survey. " + quiz_words + "\n"
                       "----------\n\n") + message
                if user_email != "unknown":
                    msg = msg + "\n\n-----------\n\nNOTE: you can write to this voter at <"\
                          +user_email+\
                          ">, but please be sure not to send them the survey link when you do so."
                msg = msg + ("\n\n"
                             "-----------\n" + quiz_words)
                mfrom = "*****@*****.**"
                if settings.DEBUG:
                    sbj = "%s to %s" % (subject,
                                        candidacy.candidate.email)
                else:
                    sbj = subject
                if settings.DEBUG:
                    mto = debug_to
                else:
                    mto = candidacy.candidate.email
                send_mail(sbj,
                          msg,
                          mfrom,
                          [mto])
            send_mail("[%s] %s" % (constituency.slug,
                                   sbj),
                      "From: %s\n\n%s" % (user_email, msg),
                      mfrom,
                      ['*****@*****.**'])
            if not request.user.is_anonymous():
                pester_action_done.send(None, user=request.user)
            for candidacy in candidacies:
                invite = candidacy.surveyinvite_set.get()
                invite.pester_emails_sent += 1
                invite.save()
            # onto thankyou page
            if no_email_candidacies:
                return render_with_context(request,
                                           'pester2.html',
                                           context)
            else:
                return render_with_context(request,
                                           'pester_thanks.html',
                                           context)
        
    return render_with_context(request,
                               'pester.html',
                               context)