from django.shortcuts import render, get_object_or_404, render, redirect
from django.views.decorators.http import require_POST
from django.contrib.auth.decorators import login_required
from django.db.models import F
import datetime
from petitions.models import Petition
from profile.models import Profile

def petition(request, petition_id):
    petition = get_object_or_404(Petition, pk=petition_id) 
    author = Profile.objects.get(petitions_created=petition)
    user = request.user
    curr_user_signed = user.partner_set.filter(petitions_signed=petition).exists()
    users_signed = Profile.objects.filter(petitions_signed=petition)
    
    data_object = {
        'petition': petition,
        'current_user': user,
        'curr_user_signed': curr_user_signed,
        'users_signed': users_signed
    }

    return render(request, '', data_object)      

@login_required
@require_POST
def petition_sign(request, petition_id):
    petition = get_object_or_404(Petition, pk=petition_id)
    user = request.user
    user.profile.petitions_signed.add(petition)
    user.save()
    petition.update(signatures=F('signatures')+1) 
    petition.update(last_signed=datetime.datetime.now())
    petition.save()
    
    return redirect('petition/' + str(petition_id))

@@ -209,16 +209,30 @@
 mport F%0A
+from datetime 
 import d
@@ -1182,25 +1182,16 @@
 atetime.
-datetime.
 now())%0A 
@@ -1266,8 +1266,618 @@
 on_id))%0A
+%0A# HELPER FUNCTIONS #%0A%0A# SORTING %0Adef most_recent():%0A    return Petition.objects.all() %5C%0A    .filter(expires__gt=datetime.now()) %5C%0A    .exclude(has_response=True) %5C%0A    .filter(published=True) %5C%0A    .order_by('-created_at')%0A%0Adef most_signatures():%0A    return Petition.objects.all() %5C%0A    .filter(expires__gt=datetime.now()) %5C%0A    .exclude(has_response=True) %5C%0A    .filter(published=True) %5C%0A    .order_by('-signatures')%0A%0Adef last_signed():%0A    return Petition.objects.all() %5C%0A    .filter(expires_gt=datetime.now()) %5C%0A    .exclude(has_response=True) %5C%0A    .filter(published=True) %5C%0A    .order_by('-last_signed')%0A

Add initial sorting functions