1 from django.http import HttpResponse
2 from forms import SandwichForm, IngredientForm
3 from django.shortcuts import render_to_response
4 from django.core.files.uploadedfile import SimpleUploadedFile
5 from models import Sandwich, Ingredient
6 from django.http import Http404
7 from django.contrib.auth import authenticate, login
8 from django.contrib.auth.forms import AuthenticationForm
12 def add_sandwich(request):
13 if request.method == 'POST': # If the form has been submitted...
14 form = SandwichForm(request.POST, request.FILES) # A form bound to the POST data
15 if form.is_valid(): # All validation rules pass
16 newsandwich = form.save()
18 thankshtml = "<p class=\"formthanks\">Thanks! Your sandwich has been added!</p>"
19 return HttpResponse(thankshtml) # Redirect after POST
21 form = SandwichForm() # An unbound form
23 return render_to_response('sandwich.html', {'sform': form,})
26 def add_ingredient(request):
27 if request.method == 'POST': # If the form has been submitted...
28 form = IngredientForm(request.POST) # A form bound to the POST data
29 if form.is_valid(): # All validation rules pass
30 newsandwich = form.save()
32 thankshtml = "<p class=\"formthanks\">Thanks! Your ingredient has been saved!</p>"
33 return HttpResponse(thankshtml) # Redirect after POST
35 form = IngredientForm() # An unbound form
37 return render_to_response('ingredient.html', {'iform': form,})
40 def all_sandwich(request):
42 sandwiches = Sandwich.objects.all()
43 except Sandwich.DoesNotExist:
45 return render_to_response('allsandwiches.html', {'sandwiches': sandwiches,})
48 def newsandwiches(request):
50 if Sandwich.objects.count() > 5:
51 sandwiches = Sandwich.objects.order_by('date_made')[:5]
53 sandwiches = Sandwich.objects.order_by('date_made')
54 except Sandwich.DoesNotExist:
56 return render_to_response('allsandwiches.html', {'sandwiches': sandwiches,})
59 def specific_sandwich(request, slug):
61 sandwiches = Sandwich.objects.get(slug=slug)
62 except Sandwich.DoesNotExist:
64 return render_to_response('onesandwich.html', {'s': sandwiches,})
67 def login_view(request):
69 username = request.POST['username']
70 password = request.POST['password']
71 user = authenticate(username=username, password=password)
75 thankshtml = "<p class=\"formthanks\">You have been logged in</p>"
76 return HttpResponse(thankshtml)
78 thankshtml = "<p class=\"formthanks\">Disabled account. Sorry.</p>"
79 return HttpResponse(thankshtml)
81 thankshtml = "<p class=\"formthanks\">Invalid login!</p>"
82 return HttpResponse(thankshtml)
84 aform = AuthenticationForm()
85 return render_to_response('login.html', {'aform': aform,})