Editing user settings works.
[~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 del_sandwich(request, slug):
92         if request.user.is_authenticated():
93                 if Sandwich.objects.get(slug=slug):
94                         del_sandwich = Sandwich.objects.get(slug=slug)
95                         if request.user == del_sandwich.user:
96                                 del_sandwich.delete()
97                         return HttpResponseRedirect(reverse('all_sandwiches'))
98                 else:
99                         return HttpResponseRedirect(reverse('all_sandwiches'))
100         else:
101                 return HttpResponseRedirect(reverse('login2'))
102
103 def add_ingredient(request):
104         if request.user.is_authenticated():
105                 if request.method == 'POST': # If the form has been submitted...
106                         form = IngredientForm(request.POST) # A form bound to the POST data
107                         if form.is_valid(): # All validation rules pass
108                                 newsandwich = form.save()
109                                 newsandwich.save()
110                                 thankshtml = "<p class=\"formthanks\">Thanks! Your ingredient has been saved!</p>"
111                                 return HttpResponse(thankshtml) # Redirect after POST
112                 else:
113                         form = IngredientForm() # An unbound form
114
115                 return render_to_response('ingredient.html', {'iform': form,}, context_instance=RequestContext(request))
116         else:
117                 thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
118                 return HttpResponse(thankshtml) # Redirect after POST
119
120 def all_sandwich(request):
121         try:
122                 allsandwiches = Sandwich.objects.order_by('-date_made')
123         except Sandwich.DoesNotExist:
124                 raise Http404
125         return render_to_response('allsandwiches.html', {'allsandwiches': allsandwiches,}, context_instance=RequestContext(request))
126
127
128 def sandwich_month(request, year, month):
129         try:
130                 ms = Sandwich.objects.filter(date_made__month=month, date_made__year=year)
131         except Sandwich.DoesNotExist:
132                 raise Http404
133         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
134         
135 def current_home(request):
136         temp = Sandwich.objects.order_by('-date_made')[0]
137         curr_month = temp.date_made.month
138         curr_year = temp.date_made.year
139         try:
140                 ms = Sandwich.objects.filter(date_made__month=curr_month, date_made__year=curr_year)
141         except Sandwich.DoesNotExist:
142                 raise Http404
143         return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
144
145
146 def specific_sandwich(request, slug):
147         try:
148                 s = Sandwich.objects.get(slug=slug)
149         except Sandwich.DoesNotExist:
150                 raise Http404
151         return render_to_response('onesandwich.html', {'s': s,}, context_instance=RequestContext(request))
152
153 def logout_view(request):
154         x = reverse('index')
155         if 'HTTP_REFERER' in request.META:
156                 x = request.META['HTTP_REFERER']
157         if request.user.is_authenticated():
158                 logout(request)
159                 return HttpResponseRedirect(x)
160         else:
161                 return HttpResponseRedirect(x)
162
163
164 def login_view(request):
165         x = reverse('index')
166         if 'HTTP_REFERER' in request.META:
167                 x = request.META['HTTP_REFERER']
168         if Sandwich.objects.count() > 5:
169                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
170         else:
171                 sandwiches = Sandwich.objects.order_by('-date_made')
172         try:
173                 username = request.POST['username']
174                 password = request.POST['password']
175                 user = authenticate(username=username, password=password)
176                 if user is not None:
177                         if user.is_active:
178                                 login(request, user)
179                                 return HttpResponseRedirect(x)
180                         else:
181                                 return HttpResponseRedirect(x)
182                 else:
183                         return HttpResponseRedirect('login')
184         except KeyError:
185                 aform = AuthenticationForm()
186                 return render_to_response('login.html', {'aform': aform,}, context_instance=RequestContext(request))
187                 
188 def login_view2(request):
189         x = reverse('index')
190         if 'HTTP_REFERER' in request.META:
191                 x = request.META['HTTP_REFERER']
192         if Sandwich.objects.count() > 5:
193                 sandwiches = Sandwich.objects.order_by('-date_made')[:5]
194         else:
195                 sandwiches = Sandwich.objects.order_by('-date_made')
196         try:
197                 username = request.POST['username']
198                 password = request.POST['password']
199                 user = authenticate(username=username, password=password)
200                 if user is not None:
201                         if user.is_active:
202                                 login(request, user)
203                                 return HttpResponseRedirect(x)
204                         else:
205                                 return HttpResponseRedirect(x)
206                 else:
207                         return HttpResponseRedirect('login2')
208         except KeyError:
209                 aform = AuthenticationForm()
210                 return render_to_response('pleaselogin.html', {'aform': aform,}, context_instance=RequestContext(request))
211
212
213 def create_user(request):
214         if request.user.is_authenticated():
215                 return HttpResponseRedirect('index')
216         elif request.method == 'POST': # If the form has been submitted...
217                 form = NewUserForm(request.POST) # A form bound to the POST data
218                 if form.is_valid(): # All validation rules pass
219                         username = form.cleaned_data['username']
220                         first_name = form.cleaned_data['first_name']
221                         last_name = form.cleaned_data['last_name']
222                         password = form.cleaned_data['password']
223                         cpassword = form.cleaned_data['confirm_password']
224                         email = form.cleaned_data['email']
225                         if password == cpassword:
226                                 user = User.objects.create_user(username, email, password)
227                                 user.save()
228                                 user.first_name = first_name
229                                 user.last_name = last_name
230                                 user.save()
231                                 return HttpResponseRedirect('index')
232                         else:
233                                 return HttpResponseRedirect('signup')   
234         else:
235                 form = NewUserForm() # An unbound form
236                 return render_to_response('newuser.html', {'cform': form,}, context_instance=RequestContext(request))
237                 
238 def edit_user(request, gusername):
239         guser = User.objects.get(username = gusername)
240         if not request.user.is_authenticated():
241                 return HttpResponseRedirect(reverse('login2'))
242         elif request.user == guser:
243                 if request.method == 'POST': # If the form has been submitted...
244                         form = NewUserForm(request.POST) # A form bound to the POST data
245                         username = request.POST['username']
246                         first_name = request.POST['first_name']
247                         last_name = request.POST['last_name']
248                         password = request.POST['password']
249                         cpassword = request.POST['confirm_password']
250                         email = request.POST['email']
251                         guser.username = username
252                         guser.first_name = first_name
253                         guser.last_name = last_name
254                         if not password.strip() == '':
255                                 if password == cpassword:
256                                         guser.set_password(password)
257                         guser.email = email
258                         guser.save()
259                         return HttpResponseRedirect(reverse('edit_user', kwargs={'gusername':guser.username}))  
260                 else:
261                         form = NewUserForm(initial={'username': guser.username, 'first_name': guser.first_name, 'last_name': guser.last_name, 'email': guser.email, }) # An unbound form
262                         return render_to_response('edituser.html', {'cform': form,}, context_instance=RequestContext(request))
263         else:
264                 return HttpResponseRedirect(reverse('index'))
265                 
266
267 def comment_posted(request):
268         if request.GET['c']:
269                 comment_id  = request.GET['c']
270                 com = Comment.objects.get( pk = comment_id )
271                 post = com.content_object
272                 if post:
273                         return HttpResponseRedirect( post.get_absolute_url() + '#comments' )
274
275
276 def ajaxfun(request):
277         if request.method == 'GET':
278                 if 'q' in request.GET:
279                         query = request.GET['q']
280                         ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
281                         responselist = []
282                         is_in = False
283                         for i in ingredients:
284                                 responselist.append({'id': str(i.pk), 'name': i.name})
285                                 if i.name == query:
286                                         is_in = True
287                         if is_in == False:
288                                 responselist.append({'id': 'new:' + query, 'name': query})
289                         response = json.dumps(responselist)
290                         return HttpResponse(response)
291                 else:
292                         return HttpResponse('{}')