Added a better slugify function, monthly archives work, notes are optional now.
authorKriti Godey <kriti.godey@gmail.com>
Fri, 5 Mar 2010 22:28:11 +0000 (17:28 -0500)
committerKriti Godey <kriti.godey@gmail.com>
Fri, 5 Mar 2010 22:28:11 +0000 (17:28 -0500)
models.py
slugify.py [new file with mode: 0644]
templates/allsandwiches.html
templates/base.html
templates/onesandwich.html
views.py

index 3139b47..37fe7dc 100644 (file)
--- a/models.py
+++ b/models.py
@@ -2,12 +2,12 @@ from django.db import models
 from django.contrib.auth.models import User
 import datetime
 from django.core.urlresolvers import reverse
-from django.template.defaultfilters import slugify
+from slugify import SlugifyUniquely
 
 
 class Ingredient(models.Model):
        name = models.CharField(max_length=100)
-       slug = models.SlugField()
+       slug = models.SlugField(unique=True)
        
        def __unicode__(self):
                return self.name
@@ -15,12 +15,12 @@ class Ingredient(models.Model):
 
 class Sandwich(models.Model):
        adjective = models.CharField(max_length=200)
-       slug = models.SlugField()
+       slug = models.SlugField(unique=True)
        date_made = models.DateField()
        ingredients = models.ManyToManyField(Ingredient)
        date_added = models.DateTimeField(default=datetime.datetime.now, editable=False)
-       picture = models.ImageField(upload_to='sandwiches/')
-       notes = models.TextField()
+       picture = models.ImageField(upload_to='sandwiches/', blank=True)
+       notes = models.TextField(blank=True)
        user = models.ForeignKey(User)
        
        class Meta:
@@ -34,5 +34,5 @@ class Sandwich(models.Model):
            return reverse('sandwich_by_slug', kwargs={'slug':self.slug})
        
        def save(self, *args, **kwargs):
-               self.slug = slugify(self.adjective)
+               self.slug = SlugifyUniquely(self.adjective, Sandwich)
                super(Sandwich, self).save(*args, **kwargs)
diff --git a/slugify.py b/slugify.py
new file mode 100644 (file)
index 0000000..5765072
--- /dev/null
@@ -0,0 +1,32 @@
+from django.template.defaultfilters import slugify
+def SlugifyUniquely(value, model, slugfield="slug"):
+        """Returns a slug on a name which is unique within a model's table
+
+        This code suffers a race condition between when a unique
+        slug is determined and when the object with that slug is saved.
+        It's also not exactly database friendly if there is a high
+        likelyhood of common slugs being attempted.
+
+        A good usage pattern for this code would be to add a custom save()
+        method to a model with a slug field along the lines of:
+
+                from django.template.defaultfilters import slugify
+
+                def save(self):
+                    if not self.id:
+                        # replace self.name with your prepopulate_from field
+                        self.slug = SlugifyUniquely(self.name, self.__class__)
+                super(self.__class__, self).save()
+
+        Original pattern discussed at
+        http://www.b-list.org/weblog/2006/11/02/django-tips-auto-populated-fields
+        """
+        suffix = 0
+        potential = base = slugify(value)
+        while True:
+                if suffix:
+                        potential = "-".join([base, str(suffix)])
+                if not model.objects.filter(**{slugfield: potential}).count():
+                        return potential
+                # we hit a conflicting slug, so bump the suffix & try again
+                suffix += 1
index 24f15b7..2a7435c 100644 (file)
@@ -1,7 +1,6 @@
 {% extends "base.html" %}
 
 {% block content %}
-       <h1 class="pagetitle">All Ma'ayanwiches</h1>
                {% for s in allsandwiches %}
                        <h3 class="sandwichtitle">{{ s.adjective }}</h3>
                        <p class="metadata">Made on {{ s.date_made }} and added by {{ s.user.username }}.</p>
@@ -14,7 +13,9 @@
                                        <li>{{ i.name }}
                                {% endfor %}
                        </ul>
-                       <h4 class="sandwichsub">Notes</h5>
-                       <p class="sandnotes"> {{ s.notes }}</p>
+                       {% if s.notes %}
+                               <h4 class="sandwichsub">Notes</h5>
+                               <p class="sandnotes"> {{ s.notes }}</p>
+                       {% endif %}
                {% endfor %}
 {% endblock %}
\ No newline at end of file
index 56fab48..a910bb1 100644 (file)
@@ -27,9 +27,9 @@
                                </ul>
                                <h3 class="navtitle">Sandwiches</h3>
                                <ul class="newest">
-                                       <li>January 2010</li>
-                                       <li>February 2010</li>
-                                       <li>To be done.</li>
+                                       {% for m in monthly %}
+                                       <li><a href="http://127.0.0.1:8000/sandwich/{{ m.year }}/{{ m.month }}/"> {{ m|date:"F" }} {{m.year}} </a></li>
+                                       {% endfor %}
                                </ul>
                                <ul class="newest">
                                        <li><a href="http://127.0.0.1:8000/sandwich/all/" class="navlink">All sandwiches</a></li>
index 1158a43..bc3c013 100644 (file)
@@ -14,6 +14,8 @@
                        <li>{{ i.name }}
                {% endfor %}
        </ul>
-       <h4 class="sandwichsub">Notes</h5>
-       <p class="sandnotes"> {{ s.notes }}</p>
+       {% if s.notes %}
+               <h4 class="sandwichsub">Notes</h5>
+               <p class="sandnotes"> {{ s.notes }}</p>
+       {% endif %}
 {% endblock %}
\ No newline at end of file
index 430446c..b84a926 100644 (file)
--- a/views.py
+++ b/views.py
@@ -10,18 +10,16 @@ from django.template import RequestContext
 import datetime
 
 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}
 
 
 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
@@ -33,17 +31,13 @@ def add_sandwich(request):
                                return HttpResponse(thankshtml) # Redirect after POST
                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
 
 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,7 +48,7 @@ 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
@@ -62,38 +56,17 @@ def add_ingredient(request):
 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()
        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 +74,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,7 +88,7 @@ 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):
        if request.user.is_authenticated():
@@ -153,7 +122,7 @@ def login_view(request):
                        return HttpResponse(thankshtml)
        except KeyError:
                aform = AuthenticationForm()
-               return render_to_response('login.html', {'aform': aform, 'user': request.user,}, context_instance=RequestContext(request))
+               return render_to_response('login.html', {'aform': aform,}, context_instance=RequestContext(request))
 
 
 def create_user(request):
@@ -186,4 +155,4 @@ def create_user(request):
                                return HttpResponse(thankshtml) # Redirect after POST   
        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))
\ No newline at end of file