Specifying a dynamic default on class declaration time can not work, because Python is only analyzing this code once your app starts and not when an actual instance is saved.
Instead override your model's save()
method to check if titulo
is empty. If it is then you can set it to user.get_username()
like this:
# models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
titulo = models.CharField(max_length=50, blank=True, default="")
descripcion = models.TextField()
def save(self, *args, **kwargs):
# If titulo is empty set it to the username.
if not self.titulo:
self.titulo = self.user.get_username()
# Now call the save() method on super to store the instance.
super(UserProfile, self).save(*args, **kwargs)
Another question is if you really want to save the username
into titulo
. That way, if a user changes her username, you have to track that and synchronize the field, which adds even more housekeeping logic into your code.
It might be easier and less error-prone to allow titulo
to be blank and in your views or templates check if it is. If yes, you can still render user.get_username()
, if not you can render titulo
.