Ingredients auto complete, adding ingredients works. Some template tweaks.
[~kgodey/maayanwich.git] / views.py
1 from django.http import HttpResponse, Http404
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 import datetime
12 import django.utils.simplejson as json
13
14 def sidebar_context(request):
15         x = Sandwich.objects.order_by('-date_made')
16         if x.count() > 5:
17                 sandwiches = x[:5]
18         else:
19                 sandwiches = x
20         monthly = Sandwich.objects.dates('date_made', 'month')
21         return {'sandwiches': sandwiches, 'monthly': monthly, 'user': request.user}
22
23
24 def add_sandwich(request):
25         if request.user.is_authenticated():
26                 if request.method == 'POST': # If the form has been submitted...
27                         form = SandwichForm(request.POST, request.FILES) # A form bound to the POST data
28                         if form.is_valid(): # All validation rules pass
29                                 newsandwich = form.save(commit=False)
30                                 newsandwich.user = request.user
31                                 newsandwich.save()
32                                 x = request.POST['ing']
33                                 x = x.strip()
34                                 y = x.split(',')
35                                 for n in y:
36                                         if n.isdigit():
37                                                 newsandwich.ingredients.add(Ingredient.objects.get(id=n))
38                                 newsandwich.save()
39                                 thankshtml = "<p class=\"formthanks\">Thanks! Your sandwich has been added!</p>"
40                                 return HttpResponse(thankshtml) # Redirect after POST
41                 else:
42                         form = SandwichForm(initial={'user': request.user}) # An unbound form
43                 return render_to_response('sandwich.html', {'sform': form,}, context_instance=RequestContext(request))
44         else:
45                 thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
46                 return HttpResponse(thankshtml) # Redirect after POST
47
48 def add_ingredient(request):
49         if request.user.is_authenticated():
50                 if request.method == 'POST': # If the form has been submitted...
51                         form = IngredientForm(request.POST) # A form bound to the POST data
52                         if form.is_valid(): # All validation rules pass
53                                 newsandwich = form.save()
54                                 newsandwich.save()
55                                 thankshtml = "<p class=\"formthanks\">Thanks! Your ingredient has been saved!</p>"
56                                 return HttpResponse(thankshtml) # Redirect after POST
57                 else:
58                         form = IngredientForm() # An unbound form
59
60                 return render_to_response('ingredient.html', {'iform': form,}, context_instance=RequestContext(request))
61         else:
62                 thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
63                 return HttpResponse(thankshtml) # Redirect after POST
64
65 def all_sandwich(request):
66         try:
67                 allsandwiches = Sandwich.objects.all()
68         except Sandwich.DoesNotExist:
69                 raise Http404
70         return render_to_response('allsandwiches.html', {'allsandwiches': allsandwiches,}, context_instance=RequestContext(request))
71
72
73 def sandwich_month(request, year, month):
74         try:
75                 ms = Sandwich.objects.filter(date_made__month=month, date_made__year=year)
76         except Sandwich.DoesNotExist:
77                 raise Http404
78         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
79         
80 def current_home(request):
81         temp = Sandwich.objects.order_by('-date_made')[0]
82         curr_month = temp.date_made.month
83         curr_year = temp.date_made.year
84         try:
85                 ms = Sandwich.objects.filter(date_made__month=curr_month, date_made__year=curr_year)
86         except Sandwich.DoesNotExist:
87                 raise Http404
88         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
89
90
91 def specific_sandwich(request, slug):
92         try:
93                 s = Sandwich.objects.get(slug=slug)
94                 if Sandwich.objects.count() > 5:
95                         sandwiches = Sandwich.objects.order_by('-date_made')[:5]
96                 else:
97                         sandwiches = Sandwich.objects.order_by('-date_made')
98         except Sandwich.DoesNotExist:
99                 raise Http404
100         return render_to_response('onesandwich.html', {'s': s,}, context_instance=RequestContext(request))
101
102 def logout_view(request):
103         if request.user.is_authenticated():
104                 logout(request)
105                 thankshtml = "<p class=\"formthanks\">You have been logged out.</p>"
106                 return HttpResponse(thankshtml)
107         else:
108                 thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
109                 return HttpResponse(thankshtml)
110
111
112 def login_view(request):
113         if Sandwich.objects.count() > 5:
114                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
115         else:
116                 sandwiches = Sandwich.objects.order_by('-date_made')
117         try:
118                 username = request.POST['username']
119                 password = request.POST['password']
120                 user = authenticate(username=username, password=password)
121                 if user is not None:
122                         if user.is_active:
123                                 login(request, user)
124                                 thankshtml = "<p class=\"formthanks\">You have been logged in</p>"
125                                 return HttpResponse(thankshtml)
126                         else:
127                                 thankshtml = "<p class=\"formthanks\">Disabled account. Sorry.</p>"
128                                 return HttpResponse(thankshtml)
129                 else:
130                         thankshtml = "<p class=\"formthanks\">Invalid login!</p>"
131                         return HttpResponse(thankshtml)
132         except KeyError:
133                 aform = AuthenticationForm()
134                 return render_to_response('login.html', {'aform': aform,}, context_instance=RequestContext(request))
135
136
137 def create_user(request):
138         if Sandwich.objects.count() > 5:
139                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
140         else:
141                 sandwiches = Sandwich.objects.order_by('-date_made')
142         if request.user.is_authenticated():
143                 thankshtml = "<p class=\"formthanks\">You are already logged in!</p>"
144                 return HttpResponse(thankshtml)
145         elif request.method == 'POST': # If the form has been submitted...
146                 form = NewUserForm(request.POST) # A form bound to the POST data
147                 if form.is_valid(): # All validation rules pass
148                         username = form.cleaned_data['username']
149                         first_name = form.cleaned_data['first_name']
150                         last_name = form.cleaned_data['last_name']
151                         password = form.cleaned_data['password']
152                         cpassword = form.cleaned_data['confirm_password']
153                         email = form.cleaned_data['email']
154                         if password == cpassword:
155                                 user = User.objects.create_user(username, email, password)
156                                 user.save()
157                                 user.first_name = first_name
158                                 user.last_name = last_name
159                                 user.save()
160                                 thankshtml = "<p class=\"formthanks\">Thanks! You are now a new user!</p>"
161                                 return HttpResponse(thankshtml) # Redirect after POST
162                         else:
163                                 thankshtml = "<p class=\"formthanks\">Your passwords don't match!</p>"
164                                 return HttpResponse(thankshtml) # Redirect after POST   
165         else:
166                 form = NewUserForm() # An unbound form
167                 return render_to_response('newuser.html', {'cform': form,}, context_instance=RequestContext(request))
168
169
170 def ajaxfun(request):
171         if request.method == 'GET':
172                 if 'q' in request.GET:
173                         query = request.GET['q']
174                         ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
175                         responselist = []
176                         for i in ingredients:
177                                 responselist.append({'id': str(i.pk), 'name': i.name})
178                         response = json.dumps(responselist)
179                         return HttpResponse(response)
180                 else:
181                         return HttpResponse('{}')