views:

490

answers:

1

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!

+3  A: 

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()
Daniel Roseman
This should work, but what if you wanted to show the user field in the form before saving it?
Do you really want to show an *editable* field for the user? It's a foreign key, so do you want a select box with all the available users, but the current one pre-selected? If so I suppose you could try overriding add_view on your ModelAdmin class to pass in an extra initial field - take a look at django.contrib.admin.options for the code.If you just want to *display* the user name, you can do that in the template using {{ request.user }}.
Daniel Roseman