Skip to content

Commit

Permalink
batch bookmark model added
Browse files Browse the repository at this point in the history
  • Loading branch information
roseva1 committed Nov 13, 2023
1 parent 12b42b1 commit 77e1e12
Show file tree
Hide file tree
Showing 5 changed files with 89 additions and 6 deletions.
1 change: 0 additions & 1 deletion turkle/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
from django.urls import path, reverse
from django.utils import timezone
from django.utils.html import format_html, format_html_join
from django.utils.translation import ngettext
from guardian.admin import GuardedModelAdmin
from guardian.shortcuts import (assign_perm, get_groups_with_perms, get_users_with_perms,
remove_perm)
Expand Down
5 changes: 5 additions & 0 deletions turkle/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,3 +938,8 @@ def completed_assignments(self):
def most_recent(self):
return self.last_finished_time
most_recent.admin_order_field = 'last_finished_time'

class Bookmark(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
batch = models.ForeignKey(Batch, on_delete=models.CASCADE)
bookmarked = models.BooleanField(default=False)
5 changes: 4 additions & 1 deletion turkle/templates/turkle/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,5 +62,8 @@

{% block footer %}
{% endblock %}

{% block script %}
{% endblock %}
</body>
</html>
</html>
40 changes: 40 additions & 0 deletions turkle/templates/turkle/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
<th>Project</th>
<th>Batch</th>
<th>Batch Published</th>
<th>Batch Bookmarked</th>
<th>Tasks Available</th>
<th></th>
<th></th>
Expand All @@ -48,6 +49,9 @@
<td>{{ batch_row.project_name }}</td>
<td>{{ batch_row.batch_name }}</td>
<td>{{ batch_row.batch_published }}</td>
<td>
<input type="checkbox" class="btn-check" id="{{ batch_row.batch_name }}" value="{{ batch_row.batch_name }}" {{ batch_row.selected}}></input>
</td>
<td>{{ batch_row.assignments_available }}</td>
<td>
<a href="{{ batch_row.preview_next_task_url }}" role="button" class="btn btn-sm btn-primary">
Expand All @@ -74,3 +78,39 @@ <h4>
</div>

{% endblock %}

{% block script %}
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
<script>
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$(document).ready(function () {
// Listen for checkbox changes
$('input[type="checkbox"]').change(function () {
$.ajax({
url: ""{% url "index" %}"",
method: 'POST', // or 'GET' depending on your needs
headers: {"X-CSRFToken": getCookie("csrftoken")},
data: {
action: 'bookmarking',
rowId: $(this).val(), // Send the value associated with the checkbox
bookmarked: $(this).is(':checked') // You can add any additional data you need
}
});
});
});
</script>
{% endblock %}
44 changes: 40 additions & 4 deletions turkle/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import urllib

from django.conf import settings
from django.contrib import messages
from django.contrib import messages, auth
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.db import connection, transaction
Expand All @@ -17,13 +17,12 @@
from django.utils.dateparse import parse_date
from django.utils.datastructures import MultiValueDictKeyError

from .models import Task, TaskAssignment, Batch, Project
from .models import Task, TaskAssignment, Batch, Project, Bookmark, User

User = get_user_model()

logger = logging.getLogger(__name__)


def handle_db_lock(func):
"""Decorator that catches database lock errors from sqlite"""
@wraps(func)
Expand All @@ -41,6 +40,12 @@ def wrapper(request, *args, **kwargs):
return wrapper


def get_user(request):
if not hasattr(request, '_cached_user'):
request._cached_user = auth.get_user(request)
return request._cached_user


def index(request):
"""
Security behavior:
Expand All @@ -63,21 +68,52 @@ def index(request):

available_task_counts = Batch.available_task_counts_for(batch_query, request.user)

if request.POST:
def process_bookmark(query_dict):
"""Create or update bookmark status for a batch & user
"""
batch_name = query_dict.get('rowId')
bookmark_status = query_dict.get('bookmarked') == 'true'
batch = Batch.objects.get(name=batch_name)
bookmark, created = Bookmark.objects.get_or_create(
user=get_user(request),
batch=batch,
defaults={'bookmarked': bookmark_status}
)
if not created:
bookmark.bookmarked = bookmark_status
bookmark.save()

if request.POST:
print(request.POST)
if 'bookmarking' in request.POST.get('action'):
process_bookmark(request.POST)

batch_rows = []
for batch in batch_query.values('created_at', 'id', 'name', 'project__name'):
total_tasks_available = available_task_counts[batch['id']]
def get_bookmark_status(batch):
"""Access batch bookmark status for a user
"""
bookmark = Bookmark.objects.filter(
user=get_user(request),
batch__name=batch['name']
).values_list('bookmarked', flat=True).first()
return 'checked' if bookmark else ''

total_tasks_available = available_task_counts[batch['id']]
if total_tasks_available > 0:
batch_rows.append({
'project_name': batch['project__name'],
'batch_name': batch['name'],
'batch_published': batch['created_at'],
'assignments_available': total_tasks_available,
'selected': get_bookmark_status(batch),
'preview_next_task_url': reverse('preview_next_task',
kwargs={'batch_id': batch['id']}),
'accept_next_task_url': reverse('accept_next_task',
kwargs={'batch_id': batch['id']})
})

return render(request, 'turkle/index.html', {
'abandoned_assignments': abandoned_assignments,
'batch_rows': batch_rows
Expand Down

0 comments on commit 77e1e12

Please sign in to comment.