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