Note that there are some explanatory texts on larger screens.

plurals
  1. PODRY way to add created/modified by and time
    primarykey
    data
    text
    <p>Having something like</p> <ul> <li>created_by </li> <li>created_date </li> <li>modified_by</li> <li>modified_date</li> </ul> <p>Would be a very common pattern for a lot of tables.</p> <p>1) You can set created date automatically (but not others) in model.py with</p> <pre><code>created_date = models.DateTimeField(auto_now_add=True, editable=False) </code></pre> <p>2) You could do created/modified dates (but not by/user as don't have request context) in model.py with</p> <pre><code>def save(self): if self.id: self.modified_date = datetime.now() else: self.created_date = datetime.now() super(MyModel,self).save() </code></pre> <p>3) You could set the created/modifed date and by in admin.py - but this doesn't deal with non admin updates</p> <pre><code>def save_model(self, request, obj, form, change): if change: obj.modified_by = request.user obj.modified_date = datetime.now() else: obj.created_by = request.user obj.created_date = datetime.now() obj.save() </code></pre> <p>4) And the final place would be in the view.py which can do all 4, but doesn't cover admin updates.</p> <p>So realistically have to have logic spread out, at a minimum repeated in 3 &amp; 4 (or a method on the model called from both, which will be missed)</p> <p>Whats a better way? (I've been working with python/django for a couple of days so could easily be missing something obvious)</p> <ul> <li>Can you do someting like @login_required e.g. @audit_changes</li> <li>Can you get access to the request and current user in the model and centralise logic there?</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload