-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathviews.py
More file actions
97 lines (72 loc) · 2.54 KB
/
views.py
File metadata and controls
97 lines (72 loc) · 2.54 KB
1
2
3
4
5
6
7
8
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# todo_list/todo_app/views.py
from django.urls import reverse, reverse_lazy
from django.views.generic import CreateView, DeleteView, ListView, UpdateView
from .models import ToDoItem, ToDoList
class ListListView(ListView):
model = ToDoList
template_name = "todo_app/index.html"
class ItemListView(ListView):
model = ToDoItem
template_name = "todo_app/todo_list.html"
def get_queryset(self):
return ToDoItem.objects.filter(todo_list_id=self.kwargs["list_id"])
def get_context_data(self):
context = super().get_context_data()
context["todo_list"] = ToDoList.objects.get(id=self.kwargs["list_id"])
return context
class ListCreate(CreateView):
model = ToDoList
fields = ["title"]
def get_context_data(self):
context = super().get_context_data()
context["title"] = "Add a new list"
return context
class ItemCreate(CreateView):
model = ToDoItem
fields = [
"todo_list",
"title",
"description",
"due_date",
]
def get_initial(self):
initial_data = super().get_initial()
todo_list = ToDoList.objects.get(id=self.kwargs["list_id"])
initial_data["todo_list"] = todo_list
return initial_data
def get_context_data(self):
context = super().get_context_data()
todo_list = ToDoList.objects.get(id=self.kwargs["list_id"])
context["todo_list"] = todo_list
context["title"] = "Create a new item"
return context
def get_success_url(self):
return reverse("list", args=[self.object.todo_list_id])
class ItemUpdate(UpdateView):
model = ToDoItem
fields = [
"todo_list",
"title",
"description",
"due_date",
]
def get_context_data(self):
context = super().get_context_data()
context["todo_list"] = self.object.todo_list
context["title"] = "Edit item"
return context
def get_success_url(self):
return reverse("list", args=[self.object.todo_list_id])
class ListDelete(DeleteView):
model = ToDoList
# You have to use reverse_lazy() instead of reverse(),
# as the urls are not loaded when the file is imported.
success_url = reverse_lazy("index")
class ItemDelete(DeleteView):
model = ToDoItem
def get_success_url(self):
return reverse_lazy("list", args=[self.kwargs["list_id"]])
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["todo_list"] = self.object.todo_list
return context