Could someone lend a hand? Instead of using the built-in admin
interface, I'm trying to build an 'admin page' of my own using
ModelForms, but the problem is that the SlugField won't prepopulate
like it does with the default admin so I've resorted to overriding the
save() method and including a method (that I got from Django Snippets)
that's supposed to slugify the title before the Entry is saved to the
database.

CODE:
def unique_slugify(instance, value, slug_field_name='slug',
queryset=None,
                   slug_separator='-'):
    """
    Calculates and stores a unique slug of ``value`` for an instance.

    ``slug_field_name`` should be a string matching the name of the
field to
    store the slug in (and the field to check against for uniqueness).

    ``queryset`` usually doesn't need to be explicitly provided -
it'll default
    to using the ``.all()`` queryset from the model's default manager.
    """
    slug_field = instance._meta.get_field(slug_field_name)

    slug = getattr(instance, slug_field.attname)
    slug_len = slug_field.max_length

    # Sort out the initial slug, limiting its length if necessary.
    slug = slugify(value)
    if slug_len:
        slug = slug[:slug_len]
    slug = _slug_strip(slug, slug_separator)
    original_slug = slug

    # Create the queryset if one wasn't explicitly provided and
exclude the
    # current instance from the queryset.
    if queryset is None:
        queryset = instance.__class__._default_manager.all()
    if instance.pk:
        queryset = queryset.exclude(pk=instance.pk)

    # Find a unique slug. If one matches, at '-2' to the end and try
again
    # (then '-3', etc).
    next = 2
    while not slug or queryset.filter(**{slug_field_name: slug}):
        slug = original_slug
        end = '%s%s' % (slug_separator, next)
        if slug_len and len(slug) + len(end) > slug_len:
            slug = slug[:slug_len-len(end)]
            slug = _slug_strip(slug, slug_separator)
        slug = '%s%s' % (slug, end)
        next += 1

    setattr(instance, slug_field.attname, slug)

def _slug_strip(value, separator='-'):
     """
     Cleans up a slug by removing slug separator characters that occur
at the
     beginning or end of a slug.

     If an alternate separator is used, it will also replace any
instances of
     the default '-' separator with the new separator.
     """
     separator = separator or ''
     if separator == '-' or not separator:
         re_sep = '-'
     else:
         re_sep = '(?:-|%s)' % re.escape(separator)
     # Remove multiple instances and if an alternate separator is
provided,
     # replace the default '-' separator.
     if separator != re_sep:
         value = re.sub('%s+' % re_sep, separator, value)
     # Remove separator from the beginning and end of the slug.
     if separator:
         if separator != '-':
             re_sep = re.escape(separator)
         value = re.sub(r'^%s+|%s+$' % (re_sep, re_sep), '', value)
     return value

class Entry(models.Model):
    title = models.CharField(max_length=250, unique=True)
    slug = models.SlugField(
        help_text="This field will be filled in automatically based on
the title field.\
                  You don't need to fill this in. Honest."
    )
    subject = models.CharField(max_length=140)
    category = models.ManyToManyField(Category)
    author = models.ForeignKey(User)
    dateTime = models.DateTimeField(default=datetime.datetime.now)
    content = models.TextField()

    class Meta:
        ordering = ['-dateTime']
        verbose_name_plural = "Entries"

    def __unicode__(self):
        return self.title

    def save(self):
        # Since I'm using a custom form, I've got to slugify by hand
        # before the model is saved.
        unique_slugify(self, "title")
        super(Entry).save()

TRACE:
Environment:

Request Method: POST
Request URL: http://localhost:42766/admin_add/
Django Version: 1.0.2 final
Python Version: 2.5.2
Installed Applications:
['django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'Blog2.Engine2']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware')

Traceback:
File "C:\Python25\Lib\site-packages\django\core\handlers\base.py" in
get_response
  86.                 response = callback(request, *callback_args,
**callback_kwargs)
File "C:\Blog2\..\Blog2\Engine2\views.py" in admin_add_entry
  48.             my_form.save()
File "C:\Python25\Lib\site-packages\django\forms\models.py" in save
  319.         return save_instance(self, self.instance,
self._meta.fields, fail_message, commit)
File "C:\Python25\Lib\site-packages\django\forms\models.py" in
save_instance
  74.         instance.save()
File "C:\Blog2\..\Blog2\Engine2\models.py" in save
  48.         super(Entry).save()

Exception Type: AttributeError at /admin_add/
Exception Value: 'super' object has no attribute 'save'

Am I not supposed to be using 'super' here?


--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to