import json from django.http import JsonResponse, HttpResponseNotFound from django.shortcuts import render from .models import Link from django.views.decorators.csrf import csrf_exempt def index(request): """ Renders a page that will load the data via JavaScript (AJAX fetch). """ return render(request, 'links/index.html') def links_list(request): """ Return JSON list of all links. """ try: page = int(request.GET.get('page', 1)) per_page = int(request.GET.get('per_page', 8)) watched = bool(request.GET.get('watched', "")) except ValueError: return JsonResponse({'error': 'Invalid page or per_page'}, status=400) offset = (page - 1) * per_page limit = offset + per_page all_links = Link.objects.all().order_by('-id') # latest first total = all_links.count() limit_results = list(all_links[offset:limit].values('id', 'url', 'watched')) results = filter(lambda row: row['watched'] == str(watched), limit_results) return JsonResponse({ 'results': results, 'total': total, 'page': page, 'per_page': per_page, 'pages': (total + per_page - 1) // per_page }) @csrf_exempt def add_link(request): """ POST endpoint to add a new link. """ if request.method == 'POST': body = json.loads(request.body) url = body.get('url') if url: link = Link.objects.create(url=url, watched=False) return JsonResponse({'id': link.id, 'url': link.url, 'watched': link.watched}, status=201) else: return JsonResponse({'error': 'URL is required'}, status=400) else: return JsonResponse({'error': 'Method not allowed'}, status=405) @csrf_exempt def delete_link(request, link_id): if request.method == 'DELETE': try: link = Link.objects.get(pk=link_id) link.delete() return JsonResponse({'status': 'deleted'}) except Link.DoesNotExist: return HttpResponseNotFound() return JsonResponse({'error': 'Method not allowed'}, status=405) @csrf_exempt def mark_watched(request, link_id): """ PATCH endpoint to mark a link as watched. """ if request.method == 'PATCH': try: link = Link.objects.get(pk=link_id) except Link.DoesNotExist: return HttpResponseNotFound() link.watched = True link.save() return JsonResponse({'id': link.id, 'url': link.url, 'watched': link.watched}) else: return JsonResponse({'error': 'Method not allowed'}, status=405)