Some more redirects. Editing user settings does not work. Overhauled adding a new...
[~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         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         
169         redirect_to = reverse('index')
170 #       if 'next' in request.GET:
171 #               redirect_to = request.GET['next']
172                 
173         if request.method == 'POST':
174                 aform = UserCreationForm(data=request.POST)
175                 if aform.is_valid():
176                         aform.save()
177                         x = authenticate(username=aform.cleaned_data['username'], password=aform.cleaned_data['password1'])
178                         login(request, x)
179                         return render_to_response('usercreated.html', context_instance=RequestContext(request))
180         else:
181                 aform = UserCreationForm()
182
183         return render_to_response('newuser.html', {'aform': aform,}, context_instance=RequestContext(request))
184
185
186 def edit_user(request, gusername):
187         guser = User.objects.get(username = gusername)
188         if not request.user.is_authenticated():
189                 return HttpResponseRedirect(reverse('login'))
190         elif request.user == guser:
191                 if request.method == 'POST': # If the form has been submitted...
192                         form = NewUserForm(request.POST) # A form bound to the POST data
193                         if form.is_valid():
194                                 username = request.POST['username']
195                                 first_name = request.POST['first_name']
196                                 last_name = request.POST['last_name']
197                                 password = request.POST['password']
198                                 cpassword = request.POST['confirmpassword']
199                                 email = request.POST['email']
200                                 guser.username = username
201                                 guser.first_name = first_name
202                                 guser.last_name = last_name
203                                 if password != '':
204                                         guser.set_password(password)
205                                 guser.email = email
206                                 guser.save()
207                                 return render_to_response('userchanged.html', context_instance=RequestContext(request)) 
208                 else:
209                         form = NewUserForm(initial={'username': guser.username, 'first_name': guser.first_name, 'last_name': guser.last_name, 'email': guser.email, }) # An unbound form
210                         return render_to_response('edituser.html', {'cform': form,}, context_instance=RequestContext(request))
211         else:
212                 return render_to_response('nopermission.html', context_instance=RequestContext(request))
213                 
214
215 def comment_posted(request):
216         if request.GET['c']:
217                 comment_id  = request.GET['c']
218                 com = Comment.objects.get( pk = comment_id )
219                 post = com.content_object
220                 if post:
221                         return HttpResponseRedirect( post.get_absolute_url() + '#comments' )
222
223
224 def ajaxfun(request):
225         if request.method == 'GET':
226                 if 'q' in request.GET:
227                         query = request.GET['q']
228                         ingredients = Ingredient.objects.filter(name__icontains=query).order_by('name')
229                         responselist = []
230                         is_in = False
231                         for i in ingredients:
232                                 responselist.append({'id': str(i.pk), 'name': i.name})
233                                 if i.name == query:
234                                         is_in = True
235                         if is_in == False:
236                                 responselist.append({'id': 'new:' + query, 'name': query})
237                         response = json.dumps(responselist)
238                         return HttpResponse(response)
239                 else:
240                         return HttpResponse('{}')