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