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