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