-
Notifications
You must be signed in to change notification settings - Fork 181
/
Copy pathviews.py
82 lines (63 loc) · 2.57 KB
/
views.py
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
from django.shortcuts import render
from django.http import HttpResponse
from rango.models import Category
from rango.models import Page
from rango.forms import CategoryForm
from django.shortcuts import redirect
from django.urls import reverse
from rango.forms import PageForm
def index(request):
category_list = Category.objects.order_by('-likes')[:5]
page_list = Page.objects.order_by('-views')[:5]
context_dict = {}
context_dict['boldmessage'] = 'Crunchy, creamy, cookie, candy, cupcake!'
context_dict['categories'] = category_list
context_dict['pages'] = page_list
context_dict['extra'] = 'From the model solution on GitHub'
return render(request, 'rango/index.html', context=context_dict)
def about(request):
# Spoiler: you don't need to pass a context dictionary here.
return render(request, 'rango/about.html')
def show_category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
context_dict['pages'] = None
context_dict['category'] = None
return render(request, 'rango/category.html', context=context_dict)
def add_category(request):
form = CategoryForm()
if request.method == 'POST':
form = CategoryForm(request.POST)
if form.is_valid():
form.save(commit=True)
return redirect('/rango/')
else:
print(form.errors)
return render(request, 'rango/add_category.html', {'form': form})
def add_page(request, category_name_slug):
try:
category = Category.objects.get(slug=category_name_slug)
except:
category = None
# You cannot add a page to a Category that does not exist... DM
if category is None:
return redirect('/rango/')
form = PageForm()
if request.method == 'POST':
form = PageForm(request.POST)
if form.is_valid():
if category:
page = form.save(commit=False)
page.category = category
page.views = 0
page.save()
return redirect(reverse('rango:show_category', kwargs={'category_name_slug': category_name_slug}))
else:
print(form.errors) # This could be better done; for the purposes of TwD, this is fine. DM.
context_dict = {'form': form, 'category': category}
return render(request, 'rango/add_page.html', context=context_dict)