Edit sandwich method added - not completely working yet. Adds a new sandwich instead...
[~kgodey/maayanwich.git] / views.py
index 430446c..554fbac 100644 (file)
--- a/views.py
+++ b/views.py
@@ -1,4 +1,4 @@
-from django.http import HttpResponse, Http404
+from django.http import HttpResponse, Http404, HttpResponseRedirect
 from django.contrib.auth.models import User
 from forms import SandwichForm, IngredientForm, NewUserForm
 from django.shortcuts import render_to_response
@@ -6,22 +6,26 @@ from django.core.files.uploadedfile import SimpleUploadedFile
 from models import Sandwich, Ingredient
 from django.contrib.auth import authenticate, login, logout
 from django.contrib.auth.forms import AuthenticationForm
+from django.contrib.comments.models import Comment
 from django.template import RequestContext
+from django.core import serializers
+from slugify import SlugifyUniquely
+from recipes.settings import MEDIA_URL
 import datetime
+import django.utils.simplejson as json
+from django.core.urlresolvers import reverse
 
 def sidebar_context(request):
-       if Sandwich.objects.count() > 5:
-               sandwiches = Sandwich.objects.order_by('-date_made')[:5]
+       x = Sandwich.objects.order_by('-date_made')
+       if x.count() > 5:
+               sandwiches = x[:5]
        else:
-               sandwiches = Sandwich.objects.order_by('-date_made')
-       return {'sandwiches': sandwiches}
+               sandwiches = x
+       monthly = Sandwich.objects.dates('date_made', 'month')
+       return {'sandwiches': sandwiches, 'monthly': monthly, 'user': request.user, 'media_url': MEDIA_URL }
 
 
 def add_sandwich(request):
-       if Sandwich.objects.count() > 5:
-               sandwiches = Sandwich.objects.order_by('-date_made')[:5]
-       else:
-               sandwiches = Sandwich.objects.order_by('-date_made')
        if request.user.is_authenticated():
                if request.method == 'POST': # If the form has been submitted...
                        form = SandwichForm(request.POST, request.FILES) # A form bound to the POST data
@@ -29,21 +33,62 @@ def add_sandwich(request):
                                newsandwich = form.save(commit=False)
                                newsandwich.user = request.user
                                newsandwich.save()
-                               thankshtml = "<p class=\"formthanks\">Thanks! Your sandwich has been added!</p>"
-                               return HttpResponse(thankshtml) # Redirect after POST
+                               x = request.POST['ing']
+                               x = x.strip()
+                               y = x.split(',')
+                               for n in y:
+                                       if n.isdigit():
+                                               newsandwich.ingredients.add(Ingredient.objects.get(id=n))
+                                       else:
+                                               n = n.lstrip('new:')
+                                               newingredient = Ingredient(name=n, slug=SlugifyUniquely(n, Ingredient))
+                                               newingredient.save()
+                                               newsandwich.ingredients.add(newingredient)
+                               newsandwich.save()
+                               return HttpResponseRedirect(newsandwich.get_absolute_url())
                else:
                        form = SandwichForm(initial={'user': request.user}) # An unbound form
-               return render_to_response('sandwich.html', {'sform': form, 'user': request.user,}, context_instance=RequestContext(request))
+               return render_to_response('sandwich.html', {'sform': form,}, context_instance=RequestContext(request))
        else:
-               thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
-               return HttpResponse(thankshtml) # Redirect after POST
+               return HttpResponseRedirect(reverse('login2'))
+               
+def edit_sandwich(request, slug):
+       sedit = Sandwich.objects.get(slug=slug)
+       if sedit.picture:
+               savedpicture = sedit.picture.url
+       if request.user.is_authenticated():
+               if not sedit.user == request.user:
+                       return HttpResponseRedirect(reverse('all_sandwiches'))
+               else:   
+                       if request.method == 'POST':
+                               sform = SandwichForm(request.POST, request.FILES, instance=sedit)
+                               if sform.is_valid(): # All validation rules pass
+                                       sform.save()
+                                       x = request.POST['ing']
+                                       x = x.strip()
+                                       y = x.split(',')
+                                       for n in y:
+                                               if n.isdigit():
+                                                       sedit.ingredients.add(Ingredient.objects.get(id=n))
+                                               else:
+                                                       n = n.lstrip('new:')
+                                                       newingredient = Ingredient(name=n, slug=SlugifyUniquely(n, Ingredient))
+                                                       newingredient.save()
+                                                       sedit.ingredients.add(newingredient)
+                                       if not sedit.picture:
+                                               if savedpicture:
+                                                       sedit.picture = savedpicture
+                                       sedit.slug = slug
+                                       sedit.save()
+                                       return HttpResponseRedirect(sedit.get_absolute_url())
+                       else:
+                               sform = SandwichForm(instance=sedit)
+                       return render_to_response('editsandwich.html', {'sform': sform, 's':sedit,}, context_instance=RequestContext(request))
+       else:
+               return HttpResponseRedirect(reverse('login2'))
 
 def add_ingredient(request):
        if request.user.is_authenticated():
-               if Sandwich.objects.count() > 5:
-                       sandwiches = Sandwich.objects.order_by('-date_made')[:5]
-               else:
-                       sandwiches = Sandwich.objects.order_by('-date_made')
                if request.method == 'POST': # If the form has been submitted...
                        form = IngredientForm(request.POST) # A form bound to the POST data
                        if form.is_valid(): # All validation rules pass
@@ -54,46 +99,25 @@ def add_ingredient(request):
                else:
                        form = IngredientForm() # An unbound form
 
-               return render_to_response('ingredient.html', {'iform': form, 'user': request.user,}, context_instance=RequestContext(request))
+               return render_to_response('ingredient.html', {'iform': form,}, context_instance=RequestContext(request))
        else:
                thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
                return HttpResponse(thankshtml) # Redirect after POST
 
 def all_sandwich(request):
        try:
-               allsandwiches = Sandwich.objects.all()
-               if Sandwich.objects.count() > 5:
-                       sandwiches = Sandwich.objects.order_by('-date_made')[:5]
-               else:
-                       sandwiches = Sandwich.objects.order_by('-date_made')
-       except Sandwich.DoesNotExist:
-               raise Http404
-       return render_to_response('allsandwiches.html', {'allsandwiches': allsandwiches, 'user': request.user,}, context_instance=RequestContext(request))
-
-
-def baseview(request):
-       try:
-               if Sandwich.objects.count() > 5:
-                       sandwiches = Sandwich.objects.order_by('-date_made')[:5]
-                       allsandwiches = Sandwich.objects.all()
-               else:
-                       sandwiches = Sandwich.objects.order_by('-date_made')
-                       allsandwiches = Sandwich.objects.all()
+               allsandwiches = Sandwich.objects.order_by('-date_made')
        except Sandwich.DoesNotExist:
                raise Http404
-       return render_to_response('base.html', {'all': allsandwiches,}, context_instance=RequestContext(request))
+       return render_to_response('allsandwiches.html', {'allsandwiches': allsandwiches,}, context_instance=RequestContext(request))
 
 
 def sandwich_month(request, year, month):
        try:
                ms = Sandwich.objects.filter(date_made__month=month, date_made__year=year)
-               if Sandwich.objects.count() > 5:
-                       sandwiches = Sandwich.objects.order_by('-date_made')[:5]
-               else:
-                       sandwiches = Sandwich.objects.order_by('-date_made')
        except Sandwich.DoesNotExist:
                raise Http404
-       return render_to_response('allsandwiches.html', {'allsandwiches': ms, 'user': request.user,}, context_instance=RequestContext(request))
+       return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
        
 def current_home(request):
        temp = Sandwich.objects.order_by('-date_made')[0]
@@ -101,13 +125,9 @@ def current_home(request):
        curr_year = temp.date_made.year
        try:
                ms = Sandwich.objects.filter(date_made__month=curr_month, date_made__year=curr_year)
-               if Sandwich.objects.count() > 5:
-                       sandwiches = Sandwich.objects.order_by('-date_made')[:5]
-               else:
-                       sandwiches = Sandwich.objects.order_by('-date_made')
        except Sandwich.DoesNotExist:
                raise Http404
-       return render_to_response('allsandwiches.html', {'allsandwiches': ms, 'user': request.user,}, context_instance=RequestContext(request))
+       return render_to_response('allsandwiches.html', {'allsandwiches': ms,}, context_instance=RequestContext(request))
 
 
 def specific_sandwich(request, slug):
@@ -119,19 +139,47 @@ def specific_sandwich(request, slug):
                        sandwiches = Sandwich.objects.order_by('-date_made')
        except Sandwich.DoesNotExist:
                raise Http404
-       return render_to_response('onesandwich.html', {'s': s, 'user': request.user,}, context_instance=RequestContext(request))
+       return render_to_response('onesandwich.html', {'s': s,}, context_instance=RequestContext(request))
 
 def logout_view(request):
+       x = reverse('index')
+       if 'HTTP_REFERER' in request.META:
+               x = request.META['HTTP_REFERER']
        if request.user.is_authenticated():
                logout(request)
-               thankshtml = "<p class=\"formthanks\">You have been logged out.</p>"
-               return HttpResponse(thankshtml)
+               return HttpResponseRedirect(x)
        else:
-               thankshtml = "<p class=\"formthanks\">You are not logged in.</p>"
-               return HttpResponse(thankshtml)
+               return HttpResponseRedirect(x)
 
 
 def login_view(request):
+       x = reverse('index')
+       if 'HTTP_REFERER' in request.META:
+               x = request.META['HTTP_REFERER']
+       if Sandwich.objects.count() > 5:
+               sandwiches = Sandwich.objects.order_by('-date_made')[:5]
+       else:
+               sandwiches = Sandwich.objects.order_by('-date_made')
+       try:
+               username = request.POST['username']
+               password = request.POST['password']
+               user = authenticate(username=username, password=password)
+               if user is not None:
+                       if user.is_active:
+                               login(request, user)
+                               return HttpResponseRedirect(x)
+                       else:
+                               return HttpResponseRedirect(x)
+               else:
+                       return HttpResponseRedirect('login')
+       except KeyError:
+               aform = AuthenticationForm()
+               return render_to_response('login.html', {'aform': aform,}, context_instance=RequestContext(request))
+               
+def login_view2(request):
+       x = reverse('index')
+       if 'HTTP_REFERER' in request.META:
+               x = request.META['HTTP_REFERER']
        if Sandwich.objects.count() > 5:
                sandwiches = Sandwich.objects.order_by('-date_made')[:5]
        else:
@@ -143,17 +191,14 @@ def login_view(request):
                if user is not None:
                        if user.is_active:
                                login(request, user)
-                               thankshtml = "<p class=\"formthanks\">You have been logged in</p>"
-                               return HttpResponse(thankshtml)
+                               return HttpResponseRedirect(x)
                        else:
-                               thankshtml = "<p class=\"formthanks\">Disabled account. Sorry.</p>"
-                               return HttpResponse(thankshtml)
+                               return HttpResponseRedirect(x)
                else:
-                       thankshtml = "<p class=\"formthanks\">Invalid login!</p>"
-                       return HttpResponse(thankshtml)
+                       return HttpResponseRedirect('login')
        except KeyError:
                aform = AuthenticationForm()
-               return render_to_response('login.html', {'aform': aform, 'user': request.user,}, context_instance=RequestContext(request))
+               return render_to_response('pleaselogin.html', {'aform': aform,}, context_instance=RequestContext(request))
 
 
 def create_user(request):
@@ -162,8 +207,7 @@ def create_user(request):
        else:
                sandwiches = Sandwich.objects.order_by('-date_made')
        if request.user.is_authenticated():
-               thankshtml = "<p class=\"formthanks\">You are already logged in!</p>"
-               return HttpResponse(thankshtml)
+               return HttpResponseRedirect('index')
        elif request.method == 'POST': # If the form has been submitted...
                form = NewUserForm(request.POST) # A form bound to the POST data
                if form.is_valid(): # All validation rules pass
@@ -179,11 +223,37 @@ def create_user(request):
                                user.first_name = first_name
                                user.last_name = last_name
                                user.save()
-                               thankshtml = "<p class=\"formthanks\">Thanks! You are now a new user!</p>"
-                               return HttpResponse(thankshtml) # Redirect after POST
+                               return HttpResponseRedirect('index')
                        else:
-                               thankshtml = "<p class=\"formthanks\">Your passwords don't match!</p>"
-                               return HttpResponse(thankshtml) # Redirect after POST   
+                               return HttpResponseRedirect('signup')   
        else:
                form = NewUserForm() # An unbound form
-               return render_to_response('newuser.html', {'cform': form, 'user': request.user,}, context_instance=RequestContext(request))
\ No newline at end of file
+               return render_to_response('newuser.html', {'cform': form,}, context_instance=RequestContext(request))
+               
+
+def comment_posted(request):
+       if request.GET['c']:
+               comment_id  = request.GET['c']
+               com = Comment.objects.get( pk = comment_id )
+               post = com.content_object
+               if post:
+                       return HttpResponseRedirect( post.get_absolute_url() + '#comments' )
+
+
+def ajaxfun(request):
+       if request.method == 'GET':
+               if 'q' in request.GET:
+                       query = request.GET['q']
+                       ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
+                       responselist = []
+                       is_in = False
+                       for i in ingredients:
+                               responselist.append({'id': str(i.pk), 'name': i.name})
+                               if i.name == query:
+                                       is_in = True
+                       if is_in == False:
+                               responselist.append({'id': 'new:' + query, 'name': query})
+                       response = json.dumps(responselist)
+                       return HttpResponse(response)
+               else:
+                       return HttpResponse('{}')
\ No newline at end of file