Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top