From 851d4e0ba5381535c55fe4347103aaa53c785606 Mon Sep 17 00:00:00 2001 From: Kriti Godey Date: Fri, 5 Mar 2010 17:28:11 -0500 Subject: [PATCH] Added a better slugify function, monthly archives work, notes are optional now. --- models.py | 12 ++++---- slugify.py | 32 +++++++++++++++++++ templates/allsandwiches.html | 7 +++-- templates/base.html | 6 ++-- templates/onesandwich.html | 6 ++-- views.py | 59 +++++++++--------------------------- 6 files changed, 63 insertions(+), 59 deletions(-) create mode 100644 slugify.py diff --git a/models.py b/models.py index 3139b47..37fe7dc 100644 --- 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 index 0000000..5765072 --- /dev/null +++ b/slugify.py @@ -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 diff --git a/templates/allsandwiches.html b/templates/allsandwiches.html index 24f15b7..2a7435c 100644 --- a/templates/allsandwiches.html +++ b/templates/allsandwiches.html @@ -1,7 +1,6 @@ {% extends "base.html" %} {% block content %} -

All Ma'ayanwiches

{% for s in allsandwiches %}

{{ s.adjective }}

Made on {{ s.date_made }} and added by {{ s.user.username }}.

@@ -14,7 +13,9 @@
  • {{ i.name }} {% endfor %} -

    Notes

    -

    {{ s.notes }}

    + {% if s.notes %} +

    Notes

    +

    {{ s.notes }}

    + {% endif %} {% endfor %} {% endblock %} \ No newline at end of file diff --git a/templates/base.html b/templates/base.html index 56fab48..a910bb1 100644 --- a/templates/base.html +++ b/templates/base.html @@ -27,9 +27,9 @@ -

    Notes

    -

    {{ s.notes }}

    + {% if s.notes %} +

    Notes

    +

    {{ s.notes }}

    + {% endif %} {% endblock %} \ No newline at end of file diff --git a/views.py b/views.py index 430446c..b84a926 100644 --- 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 = "

    You are not logged in.

    " 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 = "

    You are not logged in.

    " 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 -- 2.20.1