-1

This is my models.py file

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    toc = models.BooleanField(default=False)
    dob = models.DateField(blank=False, null=True)
    street_address = models.CharField(max_length=100, blank=False, null=False)
    city = models.CharField(max_length=100, blank=False, null=False)
    zip_code = models.PositiveIntegerField(blank=False, null=True)
    state = models.CharField(max_length=50, choices=states)
    slug = models.SlugField()
    def save(self, **kwargs):
        slug = '%s' % (self.user.username)
        unique_slugify(self, slug)
        super(UserProfile, self).save()
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])

I want to generate my UserProfile.slug from the username in User. How can I do that?

1 Answers1

0

Unless you have a good reason to write one of your own, I suggest using the slugify() method provided by django, and do something along the lines of:

def save(self, **kwargs):
    from django.utils.text import slugify

    self.slug = slugify(self.user.username)
    super(UserProfile, self).save()

This assumes you're using 1.6. The only thing that MIGHT have changed is where you import from. They like to change those things fairly often I've noticed.

Docs: https://docs.djangoproject.com/en/dev/ref/utils/#django-utils-text

skzryzg
  • 1,020
  • 8
  • 25
  • My challenge is getting it to slugify username. I can slugify any of the native fields, (ie city, state, zipcode) but grabbing username from the User model with self.user.username doesn't return results. – Daniel Kane Apr 23 '14 at 14:45
  • I just tested my code on the user model and it works. If it doesn't work for you, could you post your unique_slugify()? – skzryzg Apr 23 '14 at 15:13
  • Thanks. Actually you are right. It does work. I'm realizing my real problem is something else though I haven't figured out what yet. I got the unique_slugify from this django snippet https://djangosnippets.org/snippets/690/ – Daniel Kane Apr 23 '14 at 23:26
  • to reiterate and clarify, unique_slugify() works on all other fields? just not user.username? – skzryzg Apr 24 '14 at 05:29
  • No. I made an error. It's working with user.username. My models weren't returning the slug and I thought it had to do with that code but then I realized I screwed up registering my models in admin.py for the admin and it was interfering with the fk that extends the User model. Anyway, I got it resolved. Thanks. Sorry for the poor question. – Daniel Kane Apr 24 '14 at 22:11