38556df17e0913691e342619db040cb65930eab8
[~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('login'))
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
144 def create_user(request):
145         if Sandwich.objects.count() > 5:
146                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
147         else:
148                 sandwiches = Sandwich.objects.order_by('-date_made')
149         if request.user.is_authenticated():
150                 return HttpResponseRedirect('index')
151         elif request.method == 'POST': # If the form has been submitted...
152                 form = NewUserForm(request.POST) # A form bound to the POST data
153                 if form.is_valid(): # All validation rules pass
154                         username = form.cleaned_data['username']
155                         first_name = form.cleaned_data['first_name']
156                         last_name = form.cleaned_data['last_name']
157                         password = form.cleaned_data['password']
158                         cpassword = form.cleaned_data['confirm_password']
159                         email = form.cleaned_data['email']
160                         if password == cpassword:
161                                 user = User.objects.create_user(username, email, password)
162                                 user.save()
163                                 user.first_name = first_name
164                                 user.last_name = last_name
165                                 user.save()
166                                 return HttpResponseRedirect('index')
167                         else:
168                                 return HttpResponseRedirect('signup')   
169         else:
170                 form = NewUserForm() # An unbound form
171                 return render_to_response('newuser.html', {'cform': form,}, context_instance=RequestContext(request))
172
173
174 def ajaxfun(request):
175         if request.method == 'GET':
176                 if 'q' in request.GET:
177                         query = request.GET['q']
178                         ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
179                         responselist = []
180                         is_in = False
181                         for i in ingredients:
182                                 responselist.append({'id': str(i.pk), 'name': i.name})
183                                 if i.name == query:
184                                         is_in = True
185                         if is_in == False:
186                                 responselist.append({'id': 'new:' + query, 'name': query})
187                         response = json.dumps(responselist)
188                         return HttpResponse(response)
189                 else:
190                         return HttpResponse('{}')