Tutorial :Can a Django model automatically fill in the current authenticated user from the admin interface?



Question:

I'd like to be able to include a reference to the currently authenticated user with a Note when working with Notes from the admin interface. The model would look something like:

from django.db import models  from django.contrib.auth.models import User  from datetime import datetime        class Note(models.Model):      datetime = models.DateTimeField(default=datetime.now)      author   = models.ForeignKey(User, default=authenticated_user)      note     = models.TextField()        def __unicode__(self):          return unicode(self.author) + u' - ' + unicode(self.datetime)  

The only field that the user should see is the note text field. The datetime and author should be automagically filled in by the model, admin interface or whatever. Can this be done? Anyone have some sample code?

Thanks!


Solution:1

The setting of the date can be taken care of by specifying auto_now_add=True to the datetime field definition.

To set the user on save in the admin, do this in your admin class:

class NoteAdmin(admin.ModelAdmin):      ...usual admin options...        def save_model(self, request, obj, form, change):          obj.user = request.user          obj.save()  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »