Fakultas Ilmu Komputer UI

views.py 2.22 KB
Newer Older
1
2
from django.core.exceptions import ValidationError
from django.shortcuts import render
Izzan Fakhril Islam's avatar
Izzan Fakhril Islam committed
3
4
5
6
from .models import TodoList, TodoListCommentary
from datetime import datetime
from django.http import HttpResponseRedirect
from django.urls import reverse
7
8

# Create your views here.
Izzan Fakhril Islam's avatar
Izzan Fakhril Islam committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
todo = {}
todo_commentary = {}
HTML_FILE = "tutorial_2.html"
URL = "/tutorial-2/"
response = {
    'author': 'Izzan Fakhril Islam',
    'npm': '1606875806',
}


def index(request):
    todo_dict = TodoList.objects.all().values()
    todo_commentary_dict = TodoListCommentary.objects.all().values()
    response['todos_dict'] = convert_queryset_into_json(todo_dict)
    response['todos_commentary_dict'] = convert_queryset_into_json(todo_commentary_dict)

    return render(request, HTML_FILE, response)


def add_todo(request):
    if request.method == 'POST':
        try:
            date = datetime.strptime(request.POST['date'], '%Y-%m-%dT%H:%M')
            TodoList.objects.create(
                todo_list=request.POST['activity'],
                date=date
            )
            return HttpResponseRedirect(reverse('tutorial-2:index'))
37
38
        except (ValueError, ValidationError) as e:
            print(type(e))
Izzan Fakhril Islam's avatar
Izzan Fakhril Islam committed
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
            todo = TodoList.objects.all().values()
            response['error_msg'] = 'ERROR: Failed to add Todo List'
            response['todos_dict'] = todo

            return render(request, HTML_FILE, response)


def add_todo_commentary(request):
    if request.method == 'POST':
        try:
            date = datetime.strptime(request.POST['date'], '%Y-%m-%d')
            TodoListCommentary.objects.create(
                comment=request.POST['comment'],
                date=date
            )
            return HttpResponseRedirect(reverse('tutorial-2:index'))
55
56
        except (ValueError, ValidationError) as e:
            print(type(e))
Izzan Fakhril Islam's avatar
Izzan Fakhril Islam committed
57
58
59
60
61
62
63
64
65
66
67
68
            todo_commentary = TodoListCommentary.objects.all().values()
            response['commentary_error_msg'] = 'ERROR: Failed to add Todo List Commentary'
            response['todos_commentary_dict'] = todo_commentary

            return render(request, HTML_FILE, response)


def convert_queryset_into_json(queryset_dict):
    res = []
    for data in queryset_dict:
        res.append(data)
    return res