patrickf
patrickf

Reputation: 53

Adding a current username to 'user' field in Django model

I am working with a legacy database where all there are 'adduid' and 'moduid' fields in all tables. These fields are varchar(64).

These stamp the records with the actual userid when saved and modified. Of course when using django these fields are populated with the django db user.

What I would like is a way of populating these fields with the logged in user; preferably in the model definition.

How would I go about this? (Most solutions that I have seen rely on using a Foreign Key to the User table; however we need the actual text of the username in that field - not a fk).

thanks in advance - Patrick

Upvotes: 1

Views: 483

Answers (1)

Aidan Ewen
Aidan Ewen

Reputation: 13308

I don't think you can do this at the model level as the user isn't accessible to a Model's save method. A model can be saved without any involvement from a user (eg by a task management app such as celery). However the user is available on the HttpRequest object passed to a view, so you could do it in a view.

def your_view(request):
    # get your object
    obj.modified = request.user.username
    obj.save()

There's also a save_model function on django's ModelAdmin that you can override. Something like -

def save_model(self, request, obj, form, change):
    obj.modified = request.user.username
    obj.save()

Upvotes: 1

Related Questions