I have this small models.py file:
models.py
# -*- coding: utf-8 -*-
import datetime
from django.db import models
from django.contrib.auth.models import User
from apps.strumento.models import Strumento, Veicolo
class AllegatoStrumento(models.Model):
allegato = models.FileField(upload_to='uploads_strumento/', blank=True, null=True)
data_creazione = models.DateTimeField(default=datetime.datetime.now)
creatore = models.ForeignKey(User)
strumento = models.ForeignKey(Strumento)
class Meta:
verbose_name_plural = "Allegati strumenti"
verbose_name = "Allegato strumento"
def __unicode__(self):
return str(self.allegato)
I would like the 'creatore' field to be automatically populated with the logged user triggering the save/update action, so that I can display it but not allow it to be altered directly.
OF course, just putting the User FK like this in the model, it asks me which user to put in, which I don't want to happen.
I've tried with both these lines:
creatore = models.ForeignKey(User, default=request.user.get_username())
creatore = models.ForeignKey(User, default=User.get_username())
but none of them work, as the first misses an instance of request while the second complains that the method is NOT (corrected, thanks @bruno desthuilliers) being called on an instance ("TypeError: unbound method get_username() must be called with User instance as first argument (got nothing instead)")
What could an easy way for doing that be?