Best way to use a 'created_by' type field

Hi, I want to store who created an object in my database. So I added a created_by field on my model.
What is the most idiomatic way to make sure that when it’s created, it will have the value of self.request.user?

Make it a non-nullable foreign key and fill it wherever you create such objects. If that’s a model form, you can make it a required argument to your form class and fill it during save():

class AddThingForm(forms.ModelForm):
    class Meta:
        model = Thing
        fields = [...]

    def __init__(self, *args, creator, **kwargs):
        super().__init__(*args, **kwargs)
        self.creator = creator

    def save(self, *args, **kwargs):
        self.instance.created_by = self.creator
        return super().save(*args, **kwargs)
1 Like

Thanks… I now also found this nice pointer in the docs:

https://docs.djangoproject.com/en/3.0/topics/class-based-views/generic-editing/#models-and-request-user

It uses form_valid to populate the field.

That also works. I prefer to encapsulate all the data saving behaviour inside the form so there is no strong coupling with the view.

1 Like

To add/expand Adam’s answer a little, in addition to avoiding the “strong coupling” issue, attaching this process to the model rather than a form or view allows it to be applied when using a different form or view when creating an instance, such as the admin facility.

1 Like