added an error page for "you are not logged in"
[~kgodey/maayanwich.git] / views.py
1 from django.http import HttpResponse, Http404, HttpResponseRedirect
2 from django.contrib.auth.models import User
3 from forms import SandwichForm, IngredientForm, NewUserForm
4 from django.shortcuts import render_to_response
5 from django.core.files.uploadedfile import SimpleUploadedFile
6 from models import Sandwich, Ingredient
7 from django.contrib.auth import authenticate, login, logout
8 from django.contrib.auth.forms import AuthenticationForm
9 from django.template import RequestContext
10 from django.core import serializers
11 from slugify import SlugifyUniquely
12 from recipes.settings import MEDIA_URL
13 import datetime
14 import django.utils.simplejson as json
15 from django.core.urlresolvers import reverse
16
17 def sidebar_context(request):
18         x = Sandwich.objects.order_by('-date_made')
19         if x.count() > 5:
20                 sandwiches = x[:5]
21         else:
22                 sandwiches = x
23         monthly = Sandwich.objects.dates('date_made', 'month')
24         return {'sandwiches': sandwiches, 'monthly': monthly, 'user': request.user, 'media_url': MEDIA_URL }
25
26
27 def add_sandwich(request):
28         if request.user.is_authenticated():
29                 if request.method == 'POST': # If the form has been submitted...
30                         form = SandwichForm(request.POST, request.FILES) # A form bound to the POST data
31                         if form.is_valid(): # All validation rules pass
32                                 newsandwich = form.save(commit=False)
33                                 newsandwich.user = request.user
34                                 newsandwich.save()
35                                 x = request.POST['ing']
36                                 x = x.strip()
37                                 y = x.split(',')
38                                 for n in y:
39                                         if n.isdigit():
40                                                 newsandwich.ingredients.add(Ingredient.objects.get(id=n))
41                                         else:
42                                                 n = n.lstrip('new:')
43                                                 newingredient = Ingredient(name=n, slug=SlugifyUniquely(n, Ingredient))
44                                                 newingredient.save()
45                                                 newsandwich.ingredients.add(newingredient)
46                                 newsandwich.save()
47                                 return HttpResponseRedirect(newsandwich.get_absolute_url())
48                 else:
49                         form = SandwichForm(initial={'user': request.user}) # An unbound form
50                 return render_to_response('sandwich.html', {'sform': form,}, context_instance=RequestContext(request))
51         else:
52                 return HttpResponseRedirect(reverse('login2'))
53
54 def add_ingredient(request):
55         if request.user.is_authenticated():
56                 if request.method == 'POST': # If the form has been submitted...
57                         form = IngredientForm(request.POST) # A form bound to the POST data
58                         if form.is_valid(): # All validation rules pass
59                                 newsandwich = form.save()
60                                 newsandwich.save()
61                                 thankshtml = "<p class=\"formthanks\">Thanks! Your ingredient has been saved!</p>"
62                                 return HttpResponse(thankshtml) # Redirect after POST
63                 else:
64                         form = IngredientForm() # An unbound form
65
66                 return render_to_response('ingredient.html', {'iform': form,}, context_instance=RequestContext(request))
67         else:
68                 thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
69                 return HttpResponse(thankshtml) # Redirect after POST
70
71 def all_sandwich(request):
72         try:
73                 allsandwiches = Sandwich.objects.all()
74         except Sandwich.DoesNotExist:
75                 raise Http404
76         return render_to_response('allsandwiches.html', {'allsandwiches': allsandwiches,}, context_instance=RequestContext(request))
77
78
79 def sandwich_month(request, year, month):
80         try:
81                 ms = Sandwich.objects.filter(date_made__month=month, date_made__year=year)
82         except Sandwich.DoesNotExist:
83                 raise Http404
84         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
85         
86 def current_home(request):
87         temp = Sandwich.objects.order_by('-date_made')[0]
88         curr_month = temp.date_made.month
89         curr_year = temp.date_made.year
90         try:
91                 ms = Sandwich.objects.filter(date_made__month=curr_month, date_made__year=curr_year)
92         except Sandwich.DoesNotExist:
93                 raise Http404
94         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
95
96
97 def specific_sandwich(request, slug):
98         try:
99                 s = Sandwich.objects.get(slug=slug)
100                 if Sandwich.objects.count() > 5:
101                         sandwiches = Sandwich.objects.order_by('-date_made')[:5]
102                 else:
103                         sandwiches = Sandwich.objects.order_by('-date_made')
104         except Sandwich.DoesNotExist:
105                 raise Http404
106         return render_to_response('onesandwich.html', {'s': s,}, context_instance=RequestContext(request))
107
108 def logout_view(request):
109         x = reverse('index')
110         if 'HTTP_REFERER' in request.META:
111                 x = request.META['HTTP_REFERER']
112         if request.user.is_authenticated():
113                 logout(request)
114                 return HttpResponseRedirect(x)
115         else:
116                 return HttpResponseRedirect(x)
117
118
119 def login_view(request):
120         x = reverse('index')
121         if 'HTTP_REFERER' in request.META:
122                 x = request.META['HTTP_REFERER']
123         if Sandwich.objects.count() > 5:
124                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
125         else:
126                 sandwiches = Sandwich.objects.order_by('-date_made')
127         try:
128                 username = request.POST['username']
129                 password = request.POST['password']
130                 user = authenticate(username=username, password=password)
131                 if user is not None:
132                         if user.is_active:
133                                 login(request, user)
134                                 return HttpResponseRedirect(x)
135                         else:
136                                 return HttpResponseRedirect(x)
137                 else:
138                         return HttpResponseRedirect('login')
139         except KeyError:
140                 aform = AuthenticationForm()
141                 return render_to_response('login.html', {'aform': aform,}, context_instance=RequestContext(request))
142                 
143 def login_view2(request):
144         x = reverse('index')
145         if 'HTTP_REFERER' in request.META:
146                 x = request.META['HTTP_REFERER']
147         if Sandwich.objects.count() > 5:
148                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
149         else:
150                 sandwiches = Sandwich.objects.order_by('-date_made')
151         try:
152                 username = request.POST['username']
153                 password = request.POST['password']
154                 user = authenticate(username=username, password=password)
155                 if user is not None:
156                         if user.is_active:
157                                 login(request, user)
158                                 return HttpResponseRedirect(x)
159                         else:
160                                 return HttpResponseRedirect(x)
161                 else:
162                         return HttpResponseRedirect('login')
163         except KeyError:
164                 aform = AuthenticationForm()
165                 return render_to_response('pleaselogin.html', {'aform': aform,}, context_instance=RequestContext(request))
166
167
168 def create_user(request):
169         if Sandwich.objects.count() > 5:
170                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
171         else:
172                 sandwiches = Sandwich.objects.order_by('-date_made')
173         if request.user.is_authenticated():
174                 return HttpResponseRedirect('index')
175         elif request.method == 'POST': # If the form has been submitted...
176                 form = NewUserForm(request.POST) # A form bound to the POST data
177                 if form.is_valid(): # All validation rules pass
178                         username = form.cleaned_data['username']
179                         first_name = form.cleaned_data['first_name']
180                         last_name = form.cleaned_data['last_name']
181                         password = form.cleaned_data['password']
182                         cpassword = form.cleaned_data['confirm_password']
183                         email = form.cleaned_data['email']
184                         if password == cpassword:
185                                 user = User.objects.create_user(username, email, password)
186                                 user.save()
187                                 user.first_name = first_name
188                                 user.last_name = last_name
189                                 user.save()
190                                 return HttpResponseRedirect('index')
191                         else:
192                                 return HttpResponseRedirect('signup')   
193         else:
194                 form = NewUserForm() # An unbound form
195                 return render_to_response('newuser.html', {'cform': form,}, context_instance=RequestContext(request))
196
197
198 def ajaxfun(request):
199         if request.method == 'GET':
200                 if 'q' in request.GET:
201                         query = request.GET['q']
202                         ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
203                         responselist = []
204                         is_in = False
205                         for i in ingredients:
206                                 responselist.append({'id': str(i.pk), 'name': i.name})
207                                 if i.name == query:
208                                         is_in = True
209                         if is_in == False:
210                                 responselist.append({'id': 'new:' + query, 'name': query})
211                         response = json.dumps(responselist)
212                         return HttpResponse(response)
213                 else:
214                         return HttpResponse('{}')