Beispiel #1
0
def reorder_entries(request,compo):
	if not request.user.has_perm("compo.admin"):
		return HttpResponseNotFound()

	party = get_party(request)
	try:
		try:
			compo = Competition.objects.get(slug=compo,party=party)
		except Competition.DoesNotExist:
			raise InvalidCompetition()

	except InvalidCompetition:
		messages.add_message(request,messages.ERROR,"Invalid competition")
		return HttpResponseRedirect(reverse('compo.views.index',args=[request.party]))
	

	if request.method == "POST":
		order = request.POST.get("entry_order",None)
		if order:
			compo.jury_order = order
			compo.save()
#			messages.add_message(request,messages.SUCCESS,"Entry order updated.")
			
#	return HttpResponseRedirect(reverse('compo_jury',args=[party.slug,compo.slug]))
	return HttpResponse("ok")
Beispiel #2
0
def reorder_jury_members(request,compo):
	if not request.user.has_perm("compo.admin"):
		return HttpResponseNotFound()

	party = get_party(request)
	try:
		try:
			compo = Competition.objects.get(slug=compo,party=party)
		except Competition.DoesNotExist:
			raise InvalidCompetition()

	except InvalidCompetition:
		messages.add_message(request,messages.ERROR,"Invalid competition")
		return HttpResponseRedirect(reverse('compo.views.index',args=[request.party]))

	if request.method == "POST":
		order = request.POST.get("jury_member_order",None)
		members = JuryMember.objects.filter(compo=compo).order_by("index")
		
		i=0
		lookup = {}
		for m in members:
			lookup[str(m.id)]=m
			
		if order:
			order = order.split(',')
			for o in order:
				lookup[o].index=i
				i+=1
				lookup[o].save()
				
			messages.add_message(request,messages.SUCCESS,"Jury member order updated.")

	return HttpResponseRedirect(reverse('compo_jury',args=[party.slug,compo.slug]))
Beispiel #3
0
def participate(request, slug):
    party = get_party(request)
    sport = get_object_or_404(Sports, slug=slug)

    try:
        existing = SportsParticipant.objects.get(sport=sport, user=request.user)
    except SportsParticipant.DoesNotExist:
        existing = None

    if request.method == "POST":
        if existing:
            form = SportsParticipateForm(sport, request.POST, request.FILES, instance=existing)
        else:
            form = SportsParticipateForm(sport, request.POST, request.FILES)

        if form.is_valid():
            part = form.save(commit=False)
            part.user = request.user
            part.sport = sport
            part.save()
            messages.add_message(request, messages.SUCCESS, "Your participation was accepted.")
            return HttpResponseRedirect(reverse("sports.views.index", args=[party.slug]))

    else:
        form = SportsParticipateForm(sport)

    return render_to_response(
        "sports_participate.html", {"form": form, "sport": sport}, context_instance=RequestContext(request)
    )
Beispiel #4
0
def add_jury_member(request,compo):
	if not request.user.has_perm("compo.admin"):
		return HttpResponseNotFound()

	party = get_party(request)
	try:
		try:
			compo = Competition.objects.get(slug=compo,party=party)
		except Competition.DoesNotExist:
			raise InvalidCompetition()

	except InvalidCompetition:
		messages.add_message(request,messages.ERROR,"Invalid competition")
		return HttpResponseRedirect(reverse('compo.views.index',args=[request.party]))
	
	if request.method == "POST":
		form = JuryMemberForm(request.POST)
		if form.is_valid():
			member = form.save(commit=False)
			member.compo = compo
			member.index = JuryMember.objects.filter(compo=compo).count()
			member.save()
			messages.add_message(request,messages.SUCCESS,"Jury member '%s' added" % member.get_name())
		else:
			messages.add_message(request.messages.ERROR,"Adding jury member failed")
			
	return HttpResponseRedirect(reverse('compo_jury',args=[party.slug,compo.slug]))
Beispiel #5
0
def sport_admin(request, slug):
    party = get_party(request)

    sport = get_object_or_404(Sports, slug=slug)

    try:
        seed = SportsSeeding.objects.get(sport=sport)
    except SportsSeeding.DoesNotExist:
        seed = None

    participants = SportsParticipant.objects.filter(sport=sport).order_by("-pre_score")

    if request.method == "POST":
        form = SportsAdminForm(request.POST, instance=sport)
        if form.is_valid():
            form.save()
            messages.add_message(request, messages.SUCCESS, "Compo info updated.")
    else:
        form = SportsAdminForm(instance=sport)

    seedform = SeedForm()

    return render_to_response(
        "sports_admin.html",
        {"form": form, "sport": sport, "participants": participants, "seed": seed, "seedform": seedform},
        context_instance=RequestContext(request),
    )
Beispiel #6
0
def delete_jury_member(request,compo,id):
	if not request.user.has_perm("compo.admin"):
		return HttpResponseNotFound()

	party = get_party(request)
	try:
		try:
			compo = Competition.objects.get(slug=compo,party=party)
		except Competition.DoesNotExist:
			raise InvalidCompetition()

	except InvalidCompetition:
		messages.add_message(request,messages.ERROR,"Invalid competition")
		return HttpResponseRedirect(reverse('compo.views.index',args=[request.party]))

	try:
		member = JuryMember.objects.get(id=id)
		
		JuryPoints.objects.filter(member=member).delete()	
		member.delete()
		compo.calculate_jury_scores()
		
		messages.add_message(request,messages.SUCCESS,"jury member deleted")
	except JuryMember.DoesNotExist:
		pass
		
	return HttpResponseRedirect(reverse('compo_jury',args=[party.slug,compo.slug]))
Beispiel #7
0
def index(request):

    compolist = Competition.objects.filter(party=get_party(request))

    compos = []
    categories = []
    lookup = {}

    for compo in compolist:
        if not compo.hidden or request.user.has_perm("compo.admin"):

            if compo.category:
                if compo.category.name not in lookup:
                    categories.append({"name": compo.category.name, "compos": []})
                    lookup[compo.category.name] = len(categories) - 1
                categories[lookup[compo.category.name]]["compos"].append(compo)
            else:
                compos.append(compo)

    d = {}  # dict(compos=compos)
    if len(categories) > 0:
        d["categories"] = categories
    d["compos"] = compos

    return render_to_response("compo_index.html", d, context_instance=RequestContext(request))
Beispiel #8
0
def seed(request, slug):
    party = get_party(request)
    sport = get_object_or_404(Sports, slug=slug)

    if request.method == "POST":
        form = SeedForm(request.POST)
        if form.is_valid():
            seedtype = form.cleaned_data["seedtype"]
            num = form.cleaned_data["num"]
            minscore = form.cleaned_data["minscore"]

            participants = sport.get_participants()
            if num > len(participants):
                num = len(participants)

            if num == 0:
                messages.add_message(request, messages.ERROR, "Cannot seed. No participants")
                return HttpResponseRedirect(reverse("sports.views.sport_admin", args=[party.slug, sport.slug]))

            try:
                seed = SportsSeeding.objects.get(sport=sport)
            except SportsSeeding.DoesNotExist:
                seed = SportsSeeding(sport=sport)

            seed.max_participants = num
            seed.save()

            seed.seed(seedtype == SeedType.Random, minscore)
            seed.save()

            messages.add_message(request, messages.SUCCESS, "Seeding done.")
        else:
            messages.add_message(request, messages.ERROR, "Error in seedform")

    return HttpResponseRedirect(reverse("sports.views.sport_admin", args=[party.slug, sport.slug]))
Beispiel #9
0
def admin(request, compo):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    try:
        try:
            compo = Competition.objects.get(slug=compo, party=get_party(request))
            compo.entries = compo.get_entries()
            if request.GET.get("hidden", False):
                compo.show_hidden = True
        except Competition.DoesNotExist:
            return HttpResponseNotFound()

        if request.method == "POST":
            form = CompoAdminForm(request.POST, instance=compo)
            if form.is_valid():
                compo = form.save()
                messages.add_message(request, messages.SUCCESS, "Compo settings updated")
            else:
                messages.add_message(request, messages.ERROR, "Settings invalid")
        else:
            form = CompoAdminForm(instance=compo)

        return render_to_response(
            "compo_admin.html", dict(form=form, compo=compo), context_instance=RequestContext(request)
        )

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))
Beispiel #10
0
def results(request, slug):
    party = get_party(request)
    sport = get_object_or_404(Sports, slug=slug)

    if (sport.finished and sport.has_results()) or request.user.has_perm("sports.admin"):
        # 		return HttpResponse("")
        pass

    return HttpResponseNotFound()
Beispiel #11
0
def update_jury_score(request,compo):
	if not request.user.has_perm("compo.admin"):
		return HttpResponseNotFound()

	party = get_party(request)
	try:
		try:
			compo = Competition.objects.get(slug=compo,party=party)
		except Competition.DoesNotExist:
			raise InvalidCompetition()

	except InvalidCompetition:
		messages.add_message(request,messages.ERROR,"Invalid competition")
		return HttpResponseRedirect(reverse('compo.views.index',args=[request.party]))
	
	if request.method == "POST":
		entries = compo.get_entries().filter(hidden=False).order_by("id")
		members = JuryMember.objects.filter(compo=compo).order_by("index")
		jury_order = compo.jury_order
		if not jury_order:
			order = [e.id for e in entries]
		else:
			order = jury_order.split(',')

		jury_points_class = {}
		for e in entries:
			for m in members:
				key = "points_%d_entry_%d" % (m.id,e.id)
				points = request.POST.get(key,None)
				try:
					point = JuryPoints.objects.get(member=m,entry=e)
				except JuryPoints.DoesNotExist:
					point = JuryPoints(member=m,entry=e)
#				print key,points
				
				if points and points != "":
					try:
						point.points = int(points)
					except ValueError:
						jury_points_class[key]="error"
						point.points = None
				else:
					point.points = None
					
				point.save()
			
		compo.calculate_jury_scores()
		data = get_jury_context(compo)
		data['jury_points_class']=jury_points_class
#		return render_to_response("jury/jury_points_table.html",data,context_instance=RequestContext(request))
		
		messages.add_message(request,messages.SUCCESS,"Jury scores updated")
	
	return HttpResponseRedirect(reverse('compo_jury',args=[party.slug,compo.slug]))
Beispiel #12
0
def admin_download_entries(request, compo):
    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    if request.user.has_perm("entry.admin") or request.user.has_perm("compo.admin"):
        limit = request.GET.get("limit", None)
        if not limit:
            return render_to_response(
                "compo_admin_download_entries.html", {"compo": compo}, context_instance=RequestContext(request)
            )
        else:
            if limit == "all":
                entries = compo.get_entries().filter(hidden=False)
            elif limit == "juryed":
                entries = compo.get_entries().filter(hidden=False).filter(~Q(qualification=Qualification.Waiting))
            elif limit == "qualified":
                entries = compo.get_entries().filter(hidden=False).filter(qualification=Qualification.Qualified)
            elif limit == "publish":
                entries = (
                    compo.get_entries()
                    .filter(hidden=False)
                    .filter(~Q(qualification=Qualification.Waiting))
                    .filter(~Q(qualification=Qualification.Disqualified))
                )

            packfile = tempfile.NamedTemporaryFile(delete=False)
            pack = zipfile.ZipFile(packfile.name, "w", zipfile.ZIP_DEFLATED)

            for entry in entries:
                version = entry.get_latest_version()
                if version and version.is_file:
                    lfile = get_entry_file(version.data)
                    pack.write(lfile.name, entry.get_publish_filename())
                    os.unlink(lfile.name)
                else:
                    pack.writestr(entry.get_publish_filename(), "")

            pack.close()
            dfile = django.core.files.File(packfile)

            return serve_file(
                request, dfile, None, "%s_entries_%s.zip" % (compo.slug, limit), "application/octet-stream"
            )
    return HttpResponseNotFound()
Beispiel #13
0
	def check_ticket(request,*args,**kwargs):
		try:
		 	profile = request.user.get_profile()
			require_ticket = False
			party = get_party(request)
			if party:
				require_ticket = party.ticket_required

			if require_ticket:
				raise NoTicketError
		except NoTicketError:
			return HttpResponseRedirect(reverse('accounts.views.tickets'))
			
		return func(request,*args,**kwargs)
Beispiel #14
0
def user_info(request):
	d = dict()
	if request.user.is_authenticated():
		try:
			profile = request.user.get_profile()

			d['require_ticket']=False
			if hasattr(request,'party'):
				d['require_ticket']=get_party(request).ticket_required
				d['user_has_ticket'] = request.user.get_profile().hasPartyTicket(Party.objects.get(slug=request.party))

			d['is_organizer'] = request.user.has_perm('accounts.organizer')
		except:
			pass
	return d
Beispiel #15
0
def admin_all_results(request):
    party = get_party(request)

    if request.user.has_perm("compo.count_votes"):
        compos = Competition.objects.filter(party=party, hidden=False)

        for c in compos:
            entries = c.get_results()
            c.entries = entries

        return render_to_response(
            "compo_admin_all_results.html", {"compos": compos}, context_instance=RequestContext(request)
        )

    return HttpResponseNotFound()
Beispiel #16
0
def admin_export_all_compos(request):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    party = get_party(request)
    dom = xml.dom.minidom.getDOMImplementation().createDocument(None, "tag", None)
    compos = dom.createElement("compos")
    for compo in Competition.objects.filter(party=party):
        compos.appendChild(compo.export_xml(compo.results_public or request.user.has_perm("compo.count_votes")))

    xmldata = generate_xml(compos)
    resp = HttpResponse(content_type="text/xml")
    resp["Content-Disposition"] = 'attachment; filename="%s_compos_all_export.xml"' % party.slug.lower()

    resp.write(xmldata)
    return resp
Beispiel #17
0
def admin_edit_jury(request, compo):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    entries = compo.get_entries().filter(hidden=False).order_by("id")
    success = False
    status = ""

    if request.method == "POST":
        for entry in entries:
            # 			pkey = "entry_%d_points" % entry.id
            skey = "entry_%d_status" % entry.id
            rkey = "entry_%d_reason" % entry.id
            status = request.POST.get(skey, 0)
            # 			points = request.POST.get(pkey,0)
            reason = request.POST.get(rkey, "")
            entry.qualification = int(status)
            # 			entry.qualification_points = float(points)
            entry.qualification_text = reason
            entry.save()
        success = True
        status = "Points updated"

    entries = compo.get_entries().filter(hidden=False).order_by("id")

    data = {}

    data["entries"] = entries
    data["choices"] = QUALSTATUS
    data["compo"] = compo
    data["success"] = success
    data["status"] = status

    return render_to_response("compo_admin_jury.html", data, context_instance=RequestContext(request))
Beispiel #18
0
def admin_export_list(request, compo):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    return render_to_response(
        "compo_admin_export_list.html", {"compo": compo}, context_instance=RequestContext(request)
    )
Beispiel #19
0
def admin_edit_playlist(request, compo):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    compo = Competition.objects.get(slug=compo, party=get_party(request))
    qentries = compo.get_qualified_entries().order_by("qualification_points")

    success = False
    status = ""
    if request.method == "POST":
        places = {}
        print request.POST

        for entry in qentries:
            if entry.playlist_position != -1:
                places[str(entry.playlist_position)] = True

            key = "entry_%d" % entry.id
            place = request.POST.get(key, -1)
            if not place in places:
                places[place] = True
                entry.playlist_position = int(place)
                entry.save()
        success = True
        status = "Playlist updated."
    else:
        pass

    entries = [e for e in qentries]

    def sorter(a, b):
        if a.playlist_position == -1:
            return 1
        if b.playlist_position == -1:
            return -1
        return int(a.playlist_position - b.playlist_position)

    entries.sort(cmp=sorter)

    return render_to_response(
        "compo_admin_edit_playlist.html",
        {"compo": compo, "entries": entries, "success": success, "status": status},
        context_instance=RequestContext(request),
    )
Beispiel #20
0
def participate(request, compo):
    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    is_admin = request.user.has_perm("compo.admin")
    if (
        compo.can_submit() and (not party.ticket_required or request.user.get_profile().hasPartyTicket(party))
    ) or is_admin:

        if request.method == "POST":
            form = EntryForm(request.POST, request.FILES, compo=compo)
            if form.is_valid():
                entry = form.save(commit=False)
                entry.submitter = request.user
                entry.compo = compo
                entry.save()
                entry_submitted.send_robust(
                    sender=compo, compo=compo, entry=entry, name=entry.name, credits=entry.credits
                )

                return HttpResponseRedirect(reverse("entry.views.upload_entry_version", args=[request.party, entry.id]))
        else:
            form = EntryForm(compo=compo)

        return render_to_response(
            "compo_participate.html", {"compo": compo, "form": form}, context_instance=RequestContext(request)
        )
    else:
        if party.ticket_required and not request.user.get_profile().hasPartyTicket(party):
            messages.add_message(request, messages.ERROR, "You need ticket to participate.")
        else:
            messages.add_message(request, messages.ERROR, "Participation is closed.")

    return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))
Beispiel #21
0
def index(request):
    party = get_party(request)

    categories = SportsCategory.objects.filter(party=party).order_by("index")

    show_hidden = request.user.has_perm("sports.admin")
    for cat in categories:
        if show_hidden:
            sports = Sports.objects.filter(party=party, category=cat)
        else:
            sports = Sports.objects.filter(party=party, category=cat, hidden=False)

        if sports.count() > 0:
            cat.sports = sports
        else:
            cat.sports = None

    data = {"categories": categories}

    return render_to_response("sports_index.html", data, context_instance=RequestContext(request))
Beispiel #22
0
def tickets(request):
	party = get_party(request)
	
	if request.method == "POST":
		code = request.POST.get("code","").lstrip().rstrip()
		try:
			ticket = Ticket.objects.get(code=code)
			if ticket.used_by:
				messages.add_message(request,messages.ERROR,"Ticket is already in use")
			else:
				ticket.used_by = request.user
				ticket.save()
				messages.add_message(request,messages.SUCCESS,"Ticket added")
				
		except Ticket.DoesNotExist:
			messages.add_message(request,messages.ERROR,"Invalid ticket code")
			
	tickets = Ticket.objects.filter(used_by=request.user,party=party)
	
	return render_to_response("tickets.html",{'tickets' : tickets},context_instance=RequestContext(request))
Beispiel #23
0
def admin_results(request, compo):
    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    is_admin = request.user.has_perm("compo.count_votes")

    if compo.results_public or is_admin:
        entries = compo.get_results()

        return render_to_response(
            "compo_admin_results.html", {"compo": compo, "entries": entries}, context_instance=RequestContext(request)
        )
    else:
        return HttpResponseNotFound()
Beispiel #24
0
def admin_export_xml(request, compo):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    dom = xml.dom.minidom.getDOMImplementation().createDocument(None, "tag", None)
    compos = dom.createElement("compos")
    compos.appendChild(compo.export_xml(compo.results_public or request.user.has_perm("compo.count_votes")))
    xmldata = generate_xml(compos)

    resp = HttpResponse(content_type="text/xml")
    resp["Content-Disposition"] = 'attachment; filename="%s_%s_export.xml"' % (party.slug, compo.name.lower())
    resp.write(xmldata)
    return resp
Beispiel #25
0
def party_index(request):
	party = get_party(request)
	if party.maintenance:
		if not request.user.is_staff:
			return render_to_response("maintenance.html",context_instance=RequestContext(request))
	return render_to_response("main.html",context_instance=RequestContext(request))
Beispiel #26
0
def vote(request, compo):
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=get_party(request))
        except:
            return HttpResponseNotFound()

        if not compo.can_vote():
            messages.add_message(request, messages.ERROR, "%s voting is closed" % compo.name)
            return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

        num_places = len(compo.vote_points.split(","))
        entries = compo.get_qualified_entries()
        if len(entries) < num_places:
            num_places = len(entries)

        id_lookup = {}
        for entry in entries:
            id_lookup[str(entry.id)] = entry

        if request.method == "POST":
            try:
                uservotes = []

                for i in range(1, num_places + 1):
                    s = "place_%d" % i

                    if not s in request.POST:
                        messages.add_message(request, messages.ERROR, "You must vote for %d entries" % num_places)
                        raise VoteException()

                    entry_id = int(request.POST[s])
                    if str(entry_id) in id_lookup:
                        if str(entry_id) in uservotes:
                            messages.add_message(request, messages.ERROR, "Invalid vote")
                            raise VoteException()

                        uservotes.append(str(entry_id))

                VotePoints.objects.filter(user=request.user, compo=compo).delete()
                v = VotePoints(user=request.user, compo=compo)
                v.votes = ",".join(uservotes)
                v.submitted = datetime.now()
                v.save()

                messages.add_message(request, messages.SUCCESS, "Votes updated")
            except:
                messages.add_message(request, messages.ERROR, "Vote update failed")

        data = {"entries": entries, "has_voted": compo.user_has_voted(request.user), "compo": compo}

        data["places"] = [x for x in range(1, num_places + 1)]
        data["num_places"] = num_places

        votes = compo.get_user_votes(request.user)

        if votes:
            votes = votes.votes.split(",")
            i = 1
            for v in votes:
                if str(v) in id_lookup:
                    id_lookup[str(v)].voted = i
                    i += 1

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    return render_to_response("compo_vote.html", data, context_instance=RequestContext(request))
Beispiel #27
0
def admin_export_xsl(request, compo):
    if not request.user.has_perm("compo.admin"):
        return HttpResponseNotFound()

    party = get_party(request)
    try:
        try:
            compo = Competition.objects.get(slug=compo, party=party)
        except Competition.DoesNotExist:
            raise InvalidCompetition()

    except InvalidCompetition:
        messages.add_message(request, messages.ERROR, "Invalid competition")
        return HttpResponseRedirect(reverse("compo.views.index", args=[request.party]))

    if request.method == "POST":
        dom = xml.dom.minidom.getDOMImplementation().createDocument(None, "tag", None)
        compos = dom.createElement("compos")
        compos.appendChild(compo.export_xml(compo.results_public or request.user.has_perm("compo.count_votes")))
        xmldata = generate_xml(compos)

        xsl = ""
        uploadedFile = request.FILES["xslpacket"]
        for c in uploadedFile.chunks():
            xsl += c

        result = transform_xsl(xsl, xmldata)

        output_type = request.POST.get("output_type", "txt")

        if output_type == "txt":
            return HttpResponse(result.encode("utf-8"), mimetype="text/plain")
        elif output_type == "diploma":
            tmpxsl = tempfile.NamedTemporaryFile(delete=False)
            tmpxsl.write(xsl)
            tmpxsl.close()
            tmpdata = tempfile.NamedTemporaryFile(delete=False)
            tmpdata.write(result.encode("utf-8"))
            tmpdata.close()
            tmpout, tmpoutname = tempfile.mkstemp()
            tmpout.close()

            retcode = subprocess.call(["fop", "-xml", tmpdata.name, "-xsl", tmpxsl.name, "-pdf", tmpoutname])

            os.unlink(tmpxsl.name)
            os.unlink(tmpdata.name)
            if retcode == 0:
                outfile = open(tmpoutname)
                resp = HttpResponse(content_type="application/pdf")
                resp["Content-Disposition"] = 'attachment; filename="%s_%s_diploma_export.pdf"' % (
                    party.slug,
                    compo.name.lower(),
                )
                resp.write(outfile.read())
                outfile.close()
                os.unlink(tmpoutname)
                return resp

        elif output_type == "impress":
            odpfile = tempfile.NamedTemporaryFile(delete=False)
            for c in request.FILES["odppacket"].chunks():
                odpfile.write(c)
            # 			odpfile.close()
            archive = zipfile.ZipFile(odpfile, "a")
            archive.writestr("content.xml", result.encode("utf-8"))
            archive.close()
            result = open(odpfile.name, "r")
            resp = HttpResponse(content_type="application/octet-stream")
            resp["Content-Disposition"] = 'attachment; filename="%s_%s_export.odp"' % (party.slug, compo.name.lower())
            resp.write(result.read())
            return resp

    return HttpResponseNotFound()
Beispiel #28
0
def update_prescore(request, slug):
    party = get_party(request)
    sport = get_object_or_404(Sports, slug=slug)