0

I'm a little tricky with the new version of Django, the idea is to make an instance before you save and get the id or pk I repeat field without saving.

class User(models.Model):
    .....
    slug = models.SlugField(max_length=100, unique=True)


    def save(self, *args, **kwargs):
        """
        I'm need instance of user for access first self.pk
        """
        self.slug = self.get_slug(self.pk)
        return super(User, self).save()

The problem is still not defined "self.pk" alone will do it until you call save() that is until it is saved, the idea is to know how can I have the "self.pk" without saving earlier.

I think it could do so, but there is something wrong or not doing well, any ideas?

# My idea
def save(self, *ars, **kwargs):
    instance = super(User, self).save()
    self.slug = self.get_slug(self.pk)
    return instance

Any idea?, thanks.

Colpaisa
  • 355
  • 1
  • 4
  • 14

2 Answers2

0

The self parameter is the instance of User you want to access.

def save(self, *args, **kwargs):
    self.username  # This is username of the 
    self.slug  # This is user instance slug value
    super(User, self).save(*args, **kwargs)
aemdy
  • 3,702
  • 6
  • 34
  • 49
0

I would make a comment but i dont have enough rep.

I assume you have a slug field which must be unique? And you want to use the id(default django pk) to populate it? The django id field is AutoField witch gets the value when saved so you cant use it before you save the object.

A hack-around:

# save in the model
def save(self, *args, **kwargs):
    # get_timestamp should return a string with the current time --> unique
    self.slug = get_timestamp()
    super(User, self).save(*args, **kwargs)
    self.slug = self.get_slug(self.pk)
    super(User, self).save(*args, **kwargs)

Here an example for a timestamp string. Read the Python docs about datetime, calendar and date if you want to make your own.

Community
  • 1
  • 1
yamm
  • 1,523
  • 1
  • 15
  • 25