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