I recently started using Django and I am trying to use it as a configuration management tool for an older application that I wrote. So, I created an application in my Django project named configurations.
In order to completely answer my question above there are 2 parts to the question.
I want to add to the models.py
file in the project a class to store all the configuration values. In addition, I want to store the userid that adds a new record or updates a record as created_by
and updated_by
. I was told by someone to do the following:
"You need to establish a couple of foreign key fields in your model (eg created and updated) which both link to auth.user
. Then grab request.user
at the appropriate time and do <model>.created = request.user
and <model>.updated = request.user
just before saving."
- How do I add two foreign keys to my model properly?
I tried to complete the 1st step that he told me to complete, which is to create foreign key fields in my models.py
file which are assigned to created_by
and updated_by
. But when I try the following code, I get an error.
from django.db import models
from django.contrib.auth.models import User
class GeneralConfiguration(models.Model):
updated_by=models.ForeignKey(User)
created_by=models.ForeignKey(User)
created_timestamp=models.DateTimeField(auto_now_add=True, auto_now=False)
updated_timestamp=models.DateTimeField(auto_now_add=True, auto_now=False)
def __unicode__(self):
return "General Configuration"
The Error message shows:
jython manage.py makemigrations
←[31;1mCommandError: System check identified some issues:
ERRORS:
←[31;1mconfigurations.GeneralConfiguration.created_by: (fields.E304) Reverse acc
essor for 'GeneralConfiguration.created_by' clashes with reverse accessor for 'G
eneralConfiguration.updated_by'.
HINT: Add or change a related_name argument to the definition for 'Gener
alConfiguration.created_by' or 'GeneralConfiguration.updated_by'.←[0m
←[31;1mconfigurations.GeneralConfiguration.updated_by: (fields.E304) Reverse acc
essor for 'GeneralConfiguration.updated_by' clashes with reverse accessor for 'G
eneralConfiguration.created_by'.
HINT: Add or change a related_name argument to the definition for 'Gener
alConfiguration.updated_by' or 'GeneralConfiguration.created_by'.←[0m
←[0m
Part 2 How do I grab request.user at the appropriate time and do .created = request.user and .updated = request.user just before saving?