joeni

views.py

1
import random
2
3
from django.shortcuts import get_object_or_404, render # This allows to render the template with the view here. It's pretty cool and important.
4
from django.http import HttpResponseRedirect, HttpResponse # Why?
5
from django.core.urlresolvers import reverse # Why?
6
from django.template import loader # This allows to actually load the template.
7
from .models import * # Might make this "from . import models" but for now, this sustains.
8
from django.conf import settings
9
from django.contrib.auth.decorators import login_required
10
from django.contrib.auth import authenticate, login
11
12
# Views:
13
14
@login_required(login_url='/ITdays/authentication')
15
def index(request):
16
    """ This requires some explanation:
17
        To easily distinghuish quotes by person, each person gets a personalized color with his quote. The way this is done, is by taking the name of the person as a randomizer seed, and generating a number between 0 and 18. This is because Materialize offers 19 colors suitable for the background.
18
        When this number has been picked, then the color name associated with that number is sent to the template for rendering."""
19
    def generateColorNames(quotes):
20
    	# The names next to the code represent the name featured at http://materializecss.com/color.html. I could use the 4/5/6 color scheme of the official Material spec, but this is more than enough already.
21
        colorStrings = [
22
                "#f44336", # red
23
                "#e91e63", # pink
24
                "#9c27b0", # purple
25
                "#673ab7", # deep-purple
26
                "#3f51b5", # indigo
27
                "#2196f3", # blue
28
                "#03a9f4", # light-blue
29
                "#00bcd4", # cyan
30
                "#009688", # teal
31
                "#4caf50", # green
32
                "#8bc34a", # light-green
33
                "#cddc39", # lime
34
                "#ffeb3b", # yellow
35
                "#ffc107", # amber
36
                "#ff9800", # orange
37
                "#ff5722", # deep-orange
38
                "#795548", # brown
39
                "#9e9e9e", # grey
40
                "#607d8b", # blue-grey
41
                ]
42
        # This will be the array of colors for each author.
43
44
        colors = []
45
        for quote in quotes:
46
            random.seed(quote.author) # This will make it so that each author has the same color over all his quotes.
47
            index = random.randint(0, len(colorStrings)-1) # Adding new colors is no problem.
48
            colors.append(colorStrings[index]) # Appends the name of the color based on the generated index.
49
        return colors
50
51
    # First, we collect all the quotes, ordered by date:
52
    quotes = Quote.objects.order_by('date').filter(approved=True)
53
    
54
    # Now we also generate the colors for usage in the template:
55
    colors = generateColorNames(quotes)
56
57
    # Putting some links in the footer:
58
    footer_links = [
59
            ["Home", "/"],
60
            ["Contact", "mailto:maarten.vangeneugden@student.uhasselt.be"],
61
            ]
62
63
    # Then, we call the template that will show the quotes:
64
    # Normally we'd use the loader for that, but see below for why I don't do that.
65
    #template = loader.get_template('dit/index.html')
66
    template = 'dit/index.html'
67
68
    logins = Login.objects.order_by('date')
69
70
    # A link to view the logins:
71
    navbar_options = [
72
            ["recent_actors", "#loginsModal"],
73
            ]
74
75
    # This is the context part, where we associate the data with the different template parts.
76
    context = {
77
            'quotes': quotes, # I have to do it this way, because Django doesn't feature array indexing. Otherwise I could've used the forloop.counter0 variable.
78
            'logins': logins,
79
            'colors': colors,
80
            'materialDesign_color': "deep-purple",
81
            'materialDesign_accentColor': "amber",
82
            'navbar_title': "Quotebook",
83
            'navbar_fixed': True,
84
            'navbar_backArrow': True,
85
            'navbar_options': navbar_options,
86
            #'parallax_src': "/media/dit/parallax.jpg",  # No more parallax =3
87
            'footer_title': "Quotebook",
88
            'footer_description': "Een lijst van citaten uit 2BACH Informatica @ UHasselt.",
89
            'footer_links': footer_links,
90
            }
91
92
    # Now, normally we'd send an HTTP response, but it's kinda crufty.
93
    #return HttpResponse(template.render(context, request))
94
    # The better way to go is to return a render() (https://docs.djangoproject.com/en/1.9/intro/tutorial03/#a-shortcut-render):
95
    return render(request, template, context)
96
97
def authentication(request):
98
    if request.method == "POST":
99
        name = request.POST['name']
100
        passphrase = request.POST['password']
101
        user = authenticate(username=name, password=passphrase)
102
        if user is not None: # The user was successfully authenticated.
103
            login(request, user)
104
            # Because of Leen, I now track when and where is logged in:
105
            loginRecord = Login()
106
            loginRecord.ip = request.META['REMOTE_ADDR']
107
            loginRecord.name = name
108
            loginRecord.save()
109
            return HttpResponseRedirect(reverse('ITdays-index'))
110
111
    template = 'dit/authentication.html'
112
113
    footer_links = [
114
            ["Home", "/"],
115
            ["Contact", "mailto:maarten.vangeneugden@student.uhasselt.be"],
116
            ]
117
118
    context = {
119
            'materialDesign_color': "deep-purple",
120
            'materialDesign_accentColor': "amber",
121
            'navbar_title': "Authentication",
122
            'navbar_fixed': True,
123
            'navbar_backArrow': True,
124
            'footer_title': "Quotebook",
125
            'footer_description': "Een lijst van citaten uit 2BACH Informatica @ UHasselt.",
126
            'footer_links': footer_links,
127
            }
128
    return render(request, template, context)            
129
130
def reply(request, quoteId):
131
	relatedQuote = get_object_or_404(Quote, pk=quoteId) # Requesting the quote based on its ID. If no such quote exists, it returns a 404.
132
	
133
	try:
134
		newReply = Reaction(
135
			text = request.POST['reaction'],
136
			author = request.POST['author'],
137
			quote = relatedQuote)
138
	except (KeyError):
139
		# If any exception occurs, simply return to the index page.
140
		return HttpResponse(request.POST['reaction'])
141
	else:
142
		newReply.save() # If all goes well, save the new reply.
143
		# Always return an HttpResponseRedirect after successfully dealing with POST data. This prevents data from being posted twice if a user hits the Back button.
144
		return HttpResponseRedirect(reverse('index'))
145
146
def addQuote(request):
147
    if len(request.POST['by']) > 256:
148
        return HttpResponseRedirect(reverse('ITdays-index'))
149
150
    newQuote = Quote(
151
            text = request.POST['quote'],
152
            author = request.POST['by'],
153
            approved = True, # This will be True for now, but if it gets vandalised, I'll make it False again.
154
            )
155
156
    newQuote.save()
157
    # Always return an HttpResponseRedirect after successfully dealing with POST data. This prevents data from being posted twice if a user hits the Back button.
158
    return HttpResponseRedirect(reverse('ITdays-index'))
159