[Django]-Unable to autopopulate a Django admin field using an attribute from a OneToOne relationship

3👍

Unfortunately prepopulated_fields doesn’t accept DateTimeField, ForeignKey, nor ManyToManyField fields.

Source: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields

Possible solution, in your models.py (make slug attribute optional):

from django.utils.encoding import force_text
from django.template.defaultfilters import slugify


class UserProfile(models.Model):
    [...]
    slug = models.SlugField(blank=True, db_index=True, unique=True)

    def get_unique_slug(self, value):
        """
        Generate a valid slug for a for given string.
        """
        qs = self.__class__.objects.all()
        used = qs.values_list('slug', flat=True)
        i = 1
        baseslug = slugify(value)
        while slug in used:
            slug = '%s-%s' % (baseslug, i)
            i += 1
        return slug

    def save(self, *args, **kwargs):
        if not self.slug and self.user:
          self.slug = self.get_unique_slug(force_text(self.user.username))
        super(UserProfile, self).save(*args, **kwargs)

Leave a comment