Seite 1 von 1

[Django] Django Admin Hack / auto. setzen von User im Admin

Verfasst: Dienstag 13. November 2007, 22:57
von Panke
Hi,

ich habe das Problem, dass ich Objekten, welche durch das Admininterface verändert werden, mitgeben möchte, wer das getan hat.
Ich habe also einen ForeignKey(User) im Model, welcher automatisch gesetzt werden soll. Wie das geht steht hier.

Aber folgenden Abschnitt verstehe ich nicht.

Code: Alles auswählen

class Application(models.Model): 
    # blank=True to get the admin to work when the 
    # officer field isn't there:
    officer = models.ForeignKey(User, blank = True, default = None)
    full_name = models.CharField(maxlength = 30)
    address = models.TextField()

def save(self): 
        if getattr(self, 'officer_id', None) is None: 
            self.officer_id = threadlocals.get_current_user().id
        super(Application, self).save()

Warum bei save() auf einmal officer_id? Müsste man da nicht self.officer ein Userobject zuweisen?

Grüße
Panke

Verfasst: Montag 19. November 2007, 23:28
von sma
Hi,

Ich würde

Code: Alles auswählen

self.officer = threadlocals.get_current_user()
benutzen; ist expliziter.

Die Doku sagt:
Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column. (You can change this explicitly by specifying db_column; see db_column below.) However, your code should never have to deal with the database column name, unless you write custom SQL. You’ll always deal with the field names of your model object.
Stefan