Added delete functionality for events. Additionally, made improvements and fixed to the validation for event creation.

This commit is contained in:
vince0656 2018-06-19 15:15:42 +01:00
parent 11abbb8a64
commit 7b2ac3ec38
7 changed files with 188 additions and 33 deletions

View file

@ -27,6 +27,7 @@ urlpatterns = [
url(r'^(?P<event_id>[0-9]+)/encrypt/$', login_required(views.event_addec), name='enc-event'), url(r'^(?P<event_id>[0-9]+)/encrypt/$', login_required(views.event_addec), name='enc-event'),
url(r'^(?P<pk>[0-9]+)/launch/$', views.EventDetailLaunchView.as_view(), name='launch-event'), url(r'^(?P<pk>[0-9]+)/launch/$', views.EventDetailLaunchView.as_view(), name='launch-event'),
url(r'^edit/(?P<event_id>[0-9]+)/$', login_required(views.edit_event), name='edit-event'), url(r'^edit/(?P<event_id>[0-9]+)/$', login_required(views.edit_event), name='edit-event'),
url(r'^delete/(?P<event_id>[0-9]+)/$', login_required(views.del_event), name='del-event'),
url(r'^(?P<event_id>[0-9]+)/create/poll/$', login_required(views.manage_questions), name='create-poll'), url(r'^(?P<event_id>[0-9]+)/create/poll/$', login_required(views.manage_questions), name='create-poll'),
url(r'^(?P<event_id>[0-9]+)/poll/(?P<poll_num>[0-9]+)/$', login_required(views.view_poll), name='view-poll'), url(r'^(?P<event_id>[0-9]+)/poll/(?P<poll_num>[0-9]+)/$', login_required(views.view_poll), name='view-poll'),
url(r'^(?P<event_id>[0-9]+)/poll/(?P<poll_num>[0-9]+)/edit$', login_required(views.edit_poll), name='edit-poll'), url(r'^(?P<event_id>[0-9]+)/poll/(?P<poll_num>[0-9]+)/edit$', login_required(views.edit_poll), name='edit-poll'),

View file

@ -297,7 +297,7 @@ def create_event(request):
# TODO: Based on whether validation was successful within update model and whether # TODO: Based on whether validation was successful within update model and whether
# TODO: data was actually persisted, either perform a redirect (success) or flag an error # TODO: data was actually persisted, either perform a redirect (success) or flag an error
return HttpResponseRedirect("/event/") return HttpResponseRedirect(reverse('polls:index'))
elif request.method == "GET": elif request.method == "GET":
# Obtain context data for the rendering of the html template # Obtain context data for the rendering of the html template
events = Event.objects.all() events = Event.objects.all()
@ -354,6 +354,14 @@ def edit_event(request, event_id):
#class CreatePoll(generic.View): #class CreatePoll(generic.View):
def del_event(request, event_id):
event = get_object_or_404(Event, pk=event_id)
if request.method == "GET":
return render(request, "polls/del_event.html", {"event_title": event.title, "event_id": event.id})
elif request.method == "POST":
event.delete()
return HttpResponseRedirect(reverse('polls:index'))
def can_vote(user, event): def can_vote(user, event):
if event.voters.filter(email=user.email).exists(): if event.voters.filter(email=user.email).exists():
return True return True

View file

@ -31,7 +31,6 @@
<!-- The following UI was ported from the Election Authority UI in DEMOS1 by Vincent de Almeida --> <!-- The following UI was ported from the Election Authority UI in DEMOS1 by Vincent de Almeida -->
<!-- The DEMOS1 repository can be found at: https://github.com/mlevogiannis/demos-voting --> <!-- The DEMOS1 repository can be found at: https://github.com/mlevogiannis/demos-voting -->
<!-- TODO: look into i18n translations as this was a feature implemented in DEMOS1 --> <!-- TODO: look into i18n translations as this was a feature implemented in DEMOS1 -->
<hr/>
<div class="container"> <div class="container">
<div class="page-header"> <div class="page-header">
<h2>Create New Event with Polls</h2> <h2>Create New Event with Polls</h2>
@ -105,6 +104,9 @@
<span id="vote-end-input-error-block" class="help-block errorText"> <span id="vote-end-input-error-block" class="help-block errorText">
<!-- Errors flagged here --> <!-- Errors flagged here -->
</span> </span>
<span id="event-timings-error-block" class="help-block errorText">
<!-- Errors flagged here -->
</span>
</div> </div>
</div> </div>
<!-- Questions --> <!-- Questions -->
@ -112,7 +114,7 @@
<label for="questions-input" class="col-sm-3 col-md-2 control-label">Polls:</label> <!-- This text can be a template variable --> <label for="questions-input" class="col-sm-3 col-md-2 control-label">Polls:</label> <!-- This text can be a template variable -->
<div class="col-sm-9 col-md-10"> <div class="col-sm-9 col-md-10">
<div class="form-group"> <div class="form-group">
<table id="questions-input-table" class="table table-hover"> <table id="polls-input-table" class="table table-hover">
<thead> <thead>
<tr> <tr>
<th class="text-center">#</th> <th class="text-center">#</th>
@ -120,9 +122,9 @@
<th class="text-center">Actions</th> <th class="text-center">Actions</th>
</tr> </tr>
</thead> </thead>
<tbody class="formset questions-formset" data-formset-prefix="questions" data-formset-type="modal" data-formset-modal-title="Add a New Poll"> <tbody class="formset questions-formset" data-formset-prefix="polls" data-formset-type="modal" data-formset-modal-title="Add a New Poll">
<!-- Question / Statement --> <!-- Poll -->
<tr class="formset-form formset-form-empty hidden" data-formset-form-prefix="question"> <tr class="formset-form formset-form-empty hidden" data-formset-form-prefix="poll">
<!-- # --> <!-- # -->
<td class="formset-form-index text-center" scope=row> <td class="formset-form-index text-center" scope=row>
1 1
@ -228,7 +230,7 @@
</table> </table>
<div class="clearfix"> <div class="clearfix">
<button type="button" class="btn btn-primary formset-add" data-formset-prefix="options"> <button type="button" class="btn btn-primary formset-add" data-formset-prefix="options">
<i class="fa fa-plus-circle" aria-hidden="true"></i> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add Poll Option Add Poll Option
</button> </button>
</div> </div>
@ -245,11 +247,11 @@
<div class="row"> <div class="row">
<div class="col-xs-6"> <div class="col-xs-6">
<label class="sr-only" for="minimum-input">Minimum</label> <label class="sr-only" for="minimum-input">Minimum</label>
<input type="number" class="form-control min-input" id="minimum-input" placeholder="Minimum" value="" name="minimum-input" min="0"> <!-- TODO: Max should be set to the number of options --> <input type="number" class="form-control min-input" id="minimum-input" placeholder="Minimum" value="" name="minimum-input" min="0" max="2"> <!-- Max is the default number of options initially displayed (2) -->
</div> </div>
<div class="col-xs-6"> <div class="col-xs-6">
<label class="sr-only" for="maximum-input">Maximum</label> <label class="sr-only" for="maximum-input">Maximum</label>
<input type="number" class="form-control max-input" id="maximum-input" placeholder="Maximum" value="" name="maximum-input" min="1"> <!-- TODO: Max should be set to the number of options --> <input type="number" class="form-control max-input" id="maximum-input" placeholder="Maximum" value="" name="maximum-input" min="1" max="2"> <!-- Max is the default number of options initially displayed (2) -->
</div> </div>
</div> </div>
<span id="question-input-help-block" class="help-block"> <span id="question-input-help-block" class="help-block">
@ -265,21 +267,21 @@
</tbody> </tbody>
</table> </table>
<div class="clearfix"> <div class="clearfix">
<button type="button" class="btn btn-primary formset-add" data-formset-prefix="questions"> <button type="button" class="btn btn-primary formset-add" data-formset-prefix="polls">
<i class="fa fa-plus-circle" aria-hidden="true"></i> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add Poll Add Poll
</button> </button>
</div> </div>
<span id="question-input-help-block" class="help-block"> <span id="question-input-help-block" class="help-block">
Drag and drop to re-order polls. Drag and drop to re-order polls.
</span> </span>
<span id="question-input-error-block" class="help-block errorText"> <span id="polls-input-error-block" class="help-block errorText">
<!-- Errors flagged here --> <!-- Errors flagged here -->
</span> </span>
</div> </div>
</div> </div>
</div> </div>
<!-- Number of Polls --> <!-- { Hidden field: Number of Polls } -->
<input type="number" id="poll-count-input" name="poll-count-input" class="hidden"> <input type="number" id="poll-count-input" name="poll-count-input" class="hidden">
<!-- Organisers --> <!-- Organisers -->
<div class="form-group"> <div class="form-group">
@ -357,7 +359,7 @@
</table> </table>
<div class="clearfix"> <div class="clearfix">
<button type="button" class="btn btn-primary formset-add" data-formset-prefix="organisers"> <button type="button" class="btn btn-primary formset-add" data-formset-prefix="organisers">
<i class="fa fa-plus-circle" aria-hidden="true"></i> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add Organiser Email Add Organiser Email
</button> </button>
</div> </div>
@ -446,7 +448,7 @@
</table> </table>
<div class="clearfix"> <div class="clearfix">
<button type="button" class="btn btn-primary formset-add" data-formset-prefix="trustees"> <button type="button" class="btn btn-primary formset-add" data-formset-prefix="trustees">
<i class="fa fa-plus-circle" aria-hidden="true"></i> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>
Add Trustee Email Add Trustee Email
</button> </button>
</div> </div>
@ -468,10 +470,11 @@
Manually enter email addresses separated with commas. Alternatively, you can also upload a CSV file: Manually enter email addresses separated with commas. Alternatively, you can also upload a CSV file:
</span> </span>
<label for="files" class="btn btn-primary"> <label for="files" class="btn btn-primary">
Upload CSV <span class="glyphicon glyphicon-cloud-upload"></span>
Upload CSV
</label> </label>
<input type="file" id="files" name="file" class="btn-info"> <input type="file" id="files" name="file" class="btn-info">
<h4 id="result" class="hidden"></h4> <h4 id="result" class="hidden successText"></h4>
<span id="voters-input-error-block" class="help-block errorText"> <span id="voters-input-error-block" class="help-block errorText">
<!-- Errors flagged here --> <!-- Errors flagged here -->
</span> </span>

View file

@ -0,0 +1,27 @@
{% extends "bases/bootstrap-with-nav.html" %}
{% load staticfiles %}
{% load bootstrap3 %}
{% block content %}
<div class="container">
<div class="page-header">
<h3>Confirm Event Deletion</h3>
</div>
<div class="row">
<form method="POST" action="{% url 'polls:del-event' event_id %}" novalidate>
{% csrf_token %}
<label>Are you sure you want to delete the event '{{ event_title }}' ?</label>
<hr/>
<div class="confirm-footer">
<a href="{% url 'polls:index' %}">
<span class="btn btn-default">Cancel</span>
</a>
<input type="submit" class="btn btn-danger delete" value="Delete"/>
</div>
</form>
</div>
</div>
{% endblock %}

View file

@ -41,7 +41,7 @@
<a href="{% url 'polls:edit-event' event.id %}"> <a href="{% url 'polls:edit-event' event.id %}">
<span class="btn btn-default glyphicon glyphicon-pencil"></span> <span class="btn btn-default glyphicon glyphicon-pencil"></span>
</a> </a>
<a href="#"> <a href="{% url 'polls:del-event' event.id %}">
<span class="btn btn-default glyphicon glyphicon-trash"></span> <span class="btn btn-default glyphicon glyphicon-trash"></span>
</a> </a>
</td> </td>

View file

@ -137,13 +137,17 @@ div.formset_object {
background-image: linear-gradient(to bottom, rgb(242, 222, 222) 0, rgb(242, 203, 208) 100%); background-image: linear-gradient(to bottom, rgb(242, 222, 222) 0, rgb(242, 203, 208) 100%);
} }
/* Error */ /* Error / Success */
.errorText { .errorText {
margin-top: 0.5em; margin-top: 0.5em;
font-weight: bold; font-weight: bold;
color: red; color: red;
} }
.successText {
color: green;
}
/* File uploading */ /* File uploading */
input[type="file"] { input[type="file"] {
display: none; display: none;

View file

@ -10,13 +10,14 @@ var generalErrorBlock = document.getElementById('all-errors-help-block');
var errors = []; var errors = [];
var create = true; var create = true;
var pollCount = 0; var pollCount = 0;
var numOfOpts = 2;
function finalisePolls() { function finalisePolls() {
// Update the value of the poll count input // Update the value of the poll count input
$('#poll-count-input').val(pollCount); $('#poll-count-input').val(pollCount);
// Remove the empty and hidden poll row from the poll table // Remove the empty and hidden poll row from the poll table
var formset = $(".formset[data-formset-prefix='questions']"); var formset = $(".formset[data-formset-prefix='polls']");
var emptyForm = formset.children('.formset-form-empty'); var emptyForm = formset.children('.formset-form-empty');
emptyForm.remove(); emptyForm.remove();
} }
@ -66,12 +67,14 @@ function isFormValid() {
var slugValid = isSlugValid(); var slugValid = isSlugValid();
var voteStartValid = isVoteStartValid(); var voteStartValid = isVoteStartValid();
var voteEndValid = isVoteEndValid(); var voteEndValid = isVoteEndValid();
var eventTimingsValid = isEventTimingsValid();
var pollCountValid = isPollCountValid();
var organisersEmailsValid = areOrganisersEmailsValid(); var organisersEmailsValid = areOrganisersEmailsValid();
var trusteesEmailsValid = areTrusteesEmailsValid(); var trusteesEmailsValid = areTrusteesEmailsValid();
var votersListValid = isVotersListValid(); var votersListValid = isVotersListValid();
return nameValid && slugValid && voteStartValid && voteEndValid return nameValid && slugValid && voteStartValid && voteEndValid && pollCountValid
&& organisersEmailsValid && trusteesEmailsValid && votersListValid; && eventTimingsValid && organisersEmailsValid && trusteesEmailsValid && votersListValid;
} }
function validateFormField(validationFn, helpBlockId) { function validateFormField(validationFn, helpBlockId) {
@ -201,13 +204,14 @@ $( "#vote-start-input" ).click(function() {
}); });
function isVoteEndValid() { function isVoteEndValid() {
var helpBlockId = "vote-end-input-error-block";
var end_date_time = $('#vote-end-input').val(); var end_date_time = $('#vote-end-input').val();
var valid = isDateValid(end_date_time); var valid = isDateValid(end_date_time);
if(valid === false) { if(valid === false) {
checkAndAddError({ checkAndAddError({
error: "The voting end date and time format is invalid.", error: "The voting end date and time format is invalid.",
helpBlockId: "vote-end-input-error-block" helpBlockId: helpBlockId
}) })
} }
@ -222,10 +226,54 @@ $( "#vote-end-input" ).click(function() {
$( "#vote-end-input" ).change(); $( "#vote-end-input" ).change();
}); });
// This is different to the start and end validation functions in that it will check whether or not
// the start and end times overlap in an invalid way i.e. end time is before start etc.
function isEventTimingsValid() {
var valid = true;
var helpBlockId = "event-timings-error-block";
// Extract the string val from the vote start and end input controls
var start_date_time = $('#vote-start-input').val();
var end_date_time = $('#vote-end-input').val();
// Convert the string vals to Date objects
var start_dateObj = new Date(start_date_time);
var end_dateObj = new Date(end_date_time);
// Ensure that the start date is before the end date and that the end date is after the start date
if(!(start_dateObj < end_dateObj && end_dateObj > start_dateObj)) {
checkAndAddError({
error: "The start date must be before the end date and the end after the start date.",
helpBlockId: "event-timings-error-block"
});
valid = false;
} else {
clearError(helpBlockId);
}
return valid;
}
function isDateValid(date_time) { function isDateValid(date_time) {
return dateRegex.test(date_time); return dateRegex.test(date_time);
} }
function isPollCountValid() {
var valid = true;
if(pollCount < 1) {
checkAndAddError({
error: "You need to define at least 1 poll.",
helpBlockId: "polls-input-error-block"
});
valid = false;
}
return valid;
}
function isPollQValid() { function isPollQValid() {
var valid = true; var valid = true;
@ -249,6 +297,15 @@ function isPollOptionsValid() {
var optsInputs = $('.option-formset #option-name-input-' + pollCount); var optsInputs = $('.option-formset #option-name-input-' + pollCount);
var helpBlockId = "options-input-error-block-" + pollCount; var helpBlockId = "options-input-error-block-" + pollCount;
if(numOfOpts < 1) {
checkAndAddError({
error: "There needs to be at least 1 option",
helpBlockId: helpBlockId
});
return false;
}
var index = 0; var index = 0;
var errorStr = "Option "; var errorStr = "Option ";
for(var i = 0; i < optsInputs.length; i++) { for(var i = 0; i < optsInputs.length; i++) {
@ -287,7 +344,10 @@ function isMinMaxSelectionValid() {
var errorStr = ""; var errorStr = "";
if(minInputVal === "" || minInputVal < minInputMinAttr) { if(minInputVal === "" || minInputVal < minInputMinAttr) {
errorStr = "The minimum option selection cannot be less than " + minInputMinAttr + " or blank"; errorStr = "The minimum option selection value cannot be less than " + minInputMinAttr + " or blank";
valid = false;
} else if (minInputVal > numOfOpts) {
errorStr = "The minimum option selection value cannot be more than the number of options (" + numOfOpts + ")";
valid = false; valid = false;
} }
@ -299,7 +359,15 @@ function isMinMaxSelectionValid() {
if(errorStr !== '') { if(errorStr !== '') {
errorStr = errorStr + " and the maximum cannot be less than " + maxInputMinAttr + " or blank"; errorStr = errorStr + " and the maximum cannot be less than " + maxInputMinAttr + " or blank";
} else { } else {
errorStr = "The maximum option selection cannot be less than " + maxInputMinAttr + " or blank"; errorStr = "The maximum option selection value cannot be less than " + maxInputMinAttr + " or blank";
}
valid = false;
} else if (maxInputVal > numOfOpts) {
if (errorStr !== '') {
errorStr = errorStr + " and the same applies to the maximum";
} else {
errorStr = "The maximum option selection value (" + maxInputVal + ") cannot be more than the number of options (" + numOfOpts + ")";
} }
valid = false; valid = false;
@ -445,13 +513,14 @@ $('.trustee-formset #trustee-email-input').on('input', function(e) {
function isVotersListValid() { function isVotersListValid() {
var valid = true; var valid = true;
var helpBlockId = "voters-input-error-block";
var votersInputVal = $('#voters-list-input').val(); var votersInputVal = $('#voters-list-input').val();
// Check if the text area is blank // Check if the text area is blank
if(votersInputVal === '') { if(votersInputVal === '') {
checkAndAddError({ checkAndAddError({
error: "The voters list is blank.", error: "The voters list is blank.",
helpBlockId: "voters-input-error-block" helpBlockId: helpBlockId
}); });
return false; return false;
@ -475,7 +544,7 @@ function isVotersListValid() {
if (csvParseOutput.errors.length > 0) { if (csvParseOutput.errors.length > 0) {
checkAndAddError({ checkAndAddError({
error: "The voters list contains invalid data. It should be a csv list containing voter email addresses.", error: "The voters list contains invalid data. It should be a csv list containing voter email addresses.",
helpBlockId: "voters-input-error-block" helpBlockId: helpBlockId
}); });
return false; return false;
@ -504,7 +573,7 @@ function isVotersListValid() {
checkAndAddError({ checkAndAddError({
error: errorStr, error: errorStr,
helpBlockId: "voters-input-error-block" helpBlockId: helpBlockId
}); });
} }
@ -618,6 +687,9 @@ function processFileChange(event) {
totalNumEmails + " email(s) have been successfully uploaded."); totalNumEmails + " email(s) have been successfully uploaded.");
$('#voters-list-input').val(emails.join(', ')); $('#voters-list-input').val(emails.join(', '));
// Finally validate the form field
validateFormField(isVotersListValid, "voters-input-error-block");
} else { } else {
// There were errors, so inform the user // There were errors, so inform the user
$('#result') $('#result')
@ -721,7 +793,7 @@ function update(event, ui) {
updateFormset(formset); updateFormset(formset);
} }
$("#questions-input-table, #organisers-input-table, #trustees-input-table").sortable({ $("#polls-input-table, #organisers-input-table, #trustees-input-table").sortable({
items: "tr", items: "tr",
update: update update: update
}); });
@ -864,6 +936,28 @@ function isDialogFormValid() {
return pollQValid && optsValid && minMaxSelValid; return pollQValid && optsValid && minMaxSelValid;
} }
function updateSelectionsMaxAtrr() {
var minInput = $('#minimum-input-' + pollCount);
var maxInput = $('#maximum-input-' + pollCount);
// Get the vals from the selection inputs and update them if they exceed the new max
var minInputVal = minInput.val();
if(minInputVal !== '' && (minInputVal > numOfOpts)) {
minInput.val(numOfOpts);
}
var maxInputVal = maxInput.val();
if(maxInputVal !== '' && (maxInputVal > numOfOpts)) {
maxInput.val(numOfOpts);
}
// Finally update the max attr to include the new total num of opts
minInput.attr("max", numOfOpts);
maxInput.attr("max", numOfOpts);
}
$('.formset-add').click(function (e) { // Ported from DEMOS1 $('.formset-add').click(function (e) { // Ported from DEMOS1
var formsetPrefix = $(this).attr('data-formset-prefix'); var formsetPrefix = $(this).attr('data-formset-prefix');
var formset = $('.formset[data-formset-prefix="' + formsetPrefix + '"]'); var formset = $('.formset[data-formset-prefix="' + formsetPrefix + '"]');
@ -871,10 +965,19 @@ $('.formset-add').click(function (e) { // Ported from DEMOS1
var emptyFormCheckedInputs = emptyForm.find('input:checkbox:checked, input:radio:checked'); var emptyFormCheckedInputs = emptyForm.find('input:checkbox:checked, input:radio:checked');
var form = emptyForm.clone(true).removeClass('formset-form-empty'); var form = emptyForm.clone(true).removeClass('formset-form-empty');
// Update the IDs of the inputs of the dialogs based on the number of questions switch (formsetPrefix) {
if(formsetPrefix === "questions") { case "polls":
// Update the IDs and names of all of the cloned input form fields // Update the IDs and names of all of the cloned input form fields based on the number of polls
updateQuestionFormInputs(form); updateQuestionFormInputs(form);
// 2 is the default number shown upon the launch of the dialog
numOfOpts = 2;
break;
case "options-" + pollCount:
numOfOpts++;
updateSelectionsMaxAtrr();
clearError("options-input-error-block-" + pollCount);
break;
} }
var formIndex = formset.children('.formset-form:not(.formset-form-empty)').length; var formIndex = formset.children('.formset-form:not(.formset-form-empty)').length;
@ -912,7 +1015,13 @@ $('.formset-form-remove').click(function (e) { // Ported from DEMOS1
// Perform validation now that a row has been removed // Perform validation now that a row has been removed
switch (formPrefix) { switch (formPrefix) {
case 'poll':
// TODO: A poll has been removed so we need to update the poll count
break;
case 'option': case 'option':
// Decrement the number of total options and validate the options list
numOfOpts--;
updateSelectionsMaxAtrr();
validateFormField(isPollOptionsValid, "options-input-error-block-" + pollCount); validateFormField(isPollOptionsValid, "options-input-error-block-" + pollCount);
break; break;
case 'organiser': case 'organiser':
@ -935,7 +1044,10 @@ $('.formset-form-save').click(function (e) {
form.find('.formset-form-name:first').text(name); form.find('.formset-form-name:first').text(name);
modal.data('formSave', true); modal.data('formSave', true);
modal.modal('hide'); modal.modal('hide');
// Increment the poll count and clear any validation errors
pollCount++; pollCount++;
clearError("polls-input-error-block");
} else { } else {
//highlightErrors(); //highlightErrors();
} }