64 lines
2.2 KiB
Python
64 lines
2.2 KiB
Python
"""Display fact categories."""
|
|
import logging
|
|
|
|
from django.shortcuts import get_object_or_404, render
|
|
from rest_framework.authentication import BasicAuthentication
|
|
from rest_framework.decorators import api_view, authentication_classes, permission_classes
|
|
from rest_framework.permissions import IsAuthenticated
|
|
from rest_framework.response import Response
|
|
|
|
from facts.models import FactCategory
|
|
from facts.serializers import FactSerializer
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
|
|
@api_view(['GET'])
|
|
@authentication_classes((BasicAuthentication, ))
|
|
@permission_classes((IsAuthenticated, ))
|
|
def rpc_get_facts(request, category):
|
|
"""Get all the facts in a category."""
|
|
if request.method != 'GET':
|
|
return Response({'detail': "Supported method: GET."}, status=405)
|
|
|
|
try:
|
|
fact_category = FactCategory.objects.get(name=category)
|
|
except FactCategory.DoesNotExist:
|
|
return Response({'detail': f"Item set category '{category}' not found."}, status=404)
|
|
|
|
return Response(FactSerializer(fact_category.fact_set.all(), many=True).data)
|
|
|
|
|
|
@api_view(['GET'])
|
|
@authentication_classes((BasicAuthentication, ))
|
|
@permission_classes((IsAuthenticated, ))
|
|
def rpc_get_random_fact(request, category):
|
|
"""Get all the facts in a category."""
|
|
if request.method != 'GET':
|
|
return Response({'detail': "Supported method: GET."}, status=405)
|
|
|
|
try:
|
|
fact_category = FactCategory.objects.get(name=category)
|
|
except FactCategory.DoesNotExist:
|
|
return Response({'detail': f"Item set category '{category}' not found."}, status=404)
|
|
|
|
return Response(FactSerializer(fact_category.random_fact()).data)
|
|
|
|
|
|
def index(request):
|
|
"""Display a simple list of the fact categories, for the moment."""
|
|
factcategories = FactCategory.objects.all()
|
|
|
|
return render(request, 'facts/index.html', {'factcategories': factcategories})
|
|
|
|
|
|
def factcategory_detail(request, factcategory_name):
|
|
"""Display info, and a random choice, for the fact category."""
|
|
factcategory = get_object_or_404(FactCategory, name=factcategory_name)
|
|
|
|
facts = []
|
|
if factcategory.show_all_entries:
|
|
facts = [x.fact for x in factcategory.fact_set.all()]
|
|
|
|
return render(request, 'facts/factcategory_detail.html', {'factcategory': factcategory, 'facts': facts})
|