Lars
Lars

Reputation: 1270

Store the last edited name of user after edited

I am building a BlogApp and I am stuck on a Problem.

What i am trying to do :-

I am trying to store the last edited name of the user after edited the name. I mean, I want to store previous name after edited the new name.

BUT when i try to access the name then it shows the updated name. I also tried by saving previous name while editing but it didn't work for me.

models.py

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True)
    full_name = models.CharField(max_length=100,default='')

I also tried Tracking Who Made the Last Changes to a Model BUT i don't know how it works.

Any help would be Appreciated.

Thank You in Advance.

Upvotes: 0

Views: 56

Answers (1)

Dimitar
Dimitar

Reputation: 520

You can create your custom solution by creating a new Model which you are going to use to save the changes whenever a change is occurring.

For example, you can overwrite the save method of your model and there you can save the previous state of the name field into your newly created AccountLog(assuming it is an account) model. The fields there should connect to the model so you can back reference the log from the Account model.

This is exactly what django-auditlog does but in a more sophisticated way.

https://django-audit-log.readthedocs.io/en/latest/model_history.html

As you can see from the querying, you can see all the changes that has occurred by simply adding a audit_log = AuditLog() entry in your model.

In [2]: Product.audit_log.all()
Out[2]: [<ProductAuditLogEntry: Product: My widget changed at 2011-02-25 06:04:29.292363>,
        <ProductAuditLogEntry: Product: My widget changed at 2011-02-25 06:04:24.898991>,
        <ProductAuditLogEntry: Product: My Gadget super changed at 2011-02-25 06:04:15.448934>,
        <ProductAuditLogEntry: Product: My Gadget changed at 2011-02-25 06:04:06.566589>,
        <ProductAuditLogEntry: Product: My Gadget created at 2011-02-25 06:03:57.751222>,
        <ProductAuditLogEntry: Product: My widget created at 2011-02-25 06:03:42.027220>]

Beware that you'll probably want Tracking full model history instead of Tracking Users that Created/Modified a Model because it follows all of the changes.

Upvotes: 1

Related Questions