b5d68ff433d17cd4186df5591d7007aeca3d7663
[~kgodey/maayanwich.git] /
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 from django.contrib.auth.decorators import login_required
18
19 def sidebar_context(request):
20         x = Sandwich.objects.order_by('-date_made')
21         if x.count() > 5:
22                 sandwiches = x[:5]
23         else:
24                 sandwiches = x
25         monthly = Sandwich.objects.dates('date_made', 'month')
26         return {'sandwiches': sandwiches, 'monthly': monthly, 'user': request.user, 'media_url': MEDIA_URL }
27
28
29 @login_required
30 def add_sandwich(request):
31         if request.method == 'POST': # If the form has been submitted...
32                 form = SandwichForm(request.POST, request.FILES) # A form bound to the POST data
33                 if form.is_valid(): # All validation rules pass
34                         newsandwich = form.save(commit=False)
35                         newsandwich.user = request.user
36                         newsandwich.save()
37                         x = request.POST['ing']
38                         x = x.strip()
39                         y = x.split(',')
40                         for n in y:
41                                 if n.isdigit():
42                                         newsandwich.ingredients.add(Ingredient.objects.get(id=n))
43                                 elif n[:4] == 'new:' and len(n) > 4:
44                                         n = n.lstrip('new:')
45                                         newingredient = Ingredient(name=n, slug=SlugifyUniquely(n, Ingredient))
46                                         newingredient.save()
47                                         newsandwich.ingredients.add(newingredient)
48                         newsandwich.save()
49                         return HttpResponseRedirect(newsandwich.get_absolute_url())
50         else:
51                 form = SandwichForm(initial={'user': request.user}) # An unbound form
52         return render_to_response('sandwich.html', {'sform': form,}, context_instance=RequestContext(request))
53
54
55 @login_required
56 def edit_sandwich(request, slug):
57         sedit = Sandwich.objects.get(slug=slug)
58         ingred = sedit.ingredients.all()
59         if not sedit.user == request.user:
60                 return render_to_response('nopermission.html', context_instance=RequestContext(request))
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
89
90 @login_required
91 def del_sandwich(request, slug):
92         if Sandwich.objects.get(slug=slug):
93                 del_sandwich = Sandwich.objects.get(slug=slug)
94                 if request.user == del_sandwich.user:
95                         del_sandwich.delete()
96                 return HttpResponseRedirect(reverse('all_sandwiches'))
97         else:
98                 return HttpResponseRedirect(reverse('all_sandwiches'))
99
100
101 def all_sandwich(request):
102         try:
103                 allsandwiches = Sandwich.objects.order_by('-date_made')
104         except Sandwich.DoesNotExist:
105                 raise Http404
106         return render_to_response('allsandwiches.html', {'allsandwiches': allsandwiches,}, context_instance=RequestContext(request))
107
108
109 def sandwich_month(request, year, month):
110         try:
111                 ms = Sandwich.objects.filter(date_made__month=month, date_made__year=year)
112         except Sandwich.DoesNotExist:
113                 raise Http404
114         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
115         
116         
117 def current_home(request):
118         temp = Sandwich.objects.order_by('-date_made')[0]
119         curr_month = temp.date_made.month
120         curr_year = temp.date_made.year
121         try:
122                 ms = Sandwich.objects.filter(date_made__month=curr_month, date_made__year=curr_year)
123         except Sandwich.DoesNotExist:
124                 raise Http404
125         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
126
127
128 def specific_sandwich(request, slug):
129         try:
130                 s = Sandwich.objects.get(slug=slug)
131         except Sandwich.DoesNotExist:
132                 raise Http404
133         return render_to_response('onesandwich.html', {'s': s,}, context_instance=RequestContext(request))
134
135 def logout_view(request):
136         x = reverse('index')
137         if 'HTTP_REFERER' in request.META:
138                 x = request.META['HTTP_REFERER']
139         if request.user.is_authenticated():
140                 logout(request)
141                 return HttpResponseRedirect(x)
142         else:
143                 return render_to_response('notloggedin.html', context_instance=RequestContext(request))
144
145
146 def login_view(request):
147         if request.user.is_authenticated():
148                 return render_to_response('loggedin.html', context_instance=RequestContext(request))
149         
150         redirect_to = reverse('index')
151         if 'next' in request.GET:
152                 redirect_to = request.GET['next']
153         
154         if request.method == 'POST':
155                 aform = AuthenticationForm(data=request.POST)
156                 if aform.is_valid():
157                         login(request, aform.get_user())
158                         return HttpResponseRedirect(redirect_to)
159         else:
160                 aform = AuthenticationForm()
161         
162         return render_to_response('login.html', {'aform': aform,}, context_instance=RequestContext(request))
163
164
165 def create_user(request):
166         if request.user.is_authenticated():
167                 return render_to_response('loggedin.html', context_instance=RequestContext(request))
168         elif request.method == 'POST': # If the form has been submitted...
169                 form = NewUserForm(request.POST) # A form bound to the POST data
170                 if form.is_valid(): # All validation rules pass
171                         username = form.cleaned_data['username']
172                         first_name = form.cleaned_data['first_name']
173                         last_name = form.cleaned_data['last_name']
174                         password = form.cleaned_data['password']
175                         cpassword = form.cleaned_data['confirm_password']
176                         email = form.cleaned_data['email']
177                         if password == cpassword:
178                                 user = User.objects.create_user(username, email, password)
179                                 user.save()
180                                 user.first_name = first_name
181                                 user.last_name = last_name
182                                 user.save()
183                                 return HttpResponseRedirect('index')
184                         else:
185                                 return HttpResponseRedirect('signup')   
186         else:
187                 form = NewUserForm() # An unbound form
188                 return render_to_response('newuser.html', {'cform': form,}, context_instance=RequestContext(request))
189                 
190
191 def edit_user(request, gusername):
192         guser = User.objects.get(username = gusername)
193         if not request.user.is_authenticated():
194                 return HttpResponseRedirect(reverse('login'))
195         elif request.user == guser:
196                 if request.method == 'POST': # If the form has been submitted...
197                         form = NewUserForm(request.POST) # A form bound to the POST data
198                         username = request.POST['username']
199                         first_name = request.POST['first_name']
200                         last_name = request.POST['last_name']
201                         password = request.POST['password']
202                         cpassword = request.POST['confirm_password']
203                         email = request.POST['email']
204                         guser.username = username
205                         guser.first_name = first_name
206                         guser.last_name = last_name
207                         if not password.strip() == '':
208                                 if password == cpassword:
209                                         guser.set_password(password)
210                         guser.email = email
211                         guser.save()
212                         return HttpResponseRedirect(reverse('edit_user', kwargs={'gusername':guser.username}))  
213                 else:
214                         form = NewUserForm(initial={'username': guser.username, 'first_name': guser.first_name, 'last_name': guser.last_name, 'email': guser.email, }) # An unbound form
215                         return render_to_response('edituser.html', {'cform': form,}, context_instance=RequestContext(request))
216         else:
217                 return HttpResponseRedirect(reverse('index'))
218                 
219
220 def comment_posted(request):
221         if request.GET['c']:
222                 comment_id  = request.GET['c']
223                 com = Comment.objects.get( pk = comment_id )
224                 post = com.content_object
225                 if post:
226                         return HttpResponseRedirect( post.get_absolute_url() + '#comments' )
227
228
229 def ajaxfun(request):
230         if request.method == 'GET':
231                 if 'q' in request.GET:
232                         query = request.GET['q']
233                         ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
234                         responselist = []
235                         is_in = False
236                         for i in ingredients:
237                                 responselist.append({'id': str(i.pk), 'name': i.name})
238                                 if i.name == query:
239                                         is_in = True
240                         if is_in == False:
241                                 responselist.append({'id': 'new:' + query, 'name': query})
242                         response = json.dumps(responselist)
243                         return HttpResponse(response)
244                 else:
245                         return HttpResponse('{}')