4

Basically I want a way to have the admins leave comments on the model being viewed. Let's say we have a model Car which I have registered within the admin site and I want to allow the other admins to write a short note about this car and have it show up ONLY IN THE ADMIN INTERFACE along with their name and a timestamp.

Essentially I want to add a commenting form in the django admin for a specific model.

Any suggestions on how to do this without overriding the entire view?

Round 2 (EDIT)

This is my progress using GordonsBeards answer.

how my admin looks now

It is adding 3 "extra" empty notes which is not a deal breaker but is interesting none the less.

# In models.py
class Note(models.Model):
    user = models.ForeignKey(User)
    note = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return "created on: {}".format(self.created_on)

My User model handles both admin users and is what I want to add the notes functionality on. How would I add the logged in users name in front of the created on date?

4
  • To remove the extra fields, in your NotesInline add extra = 0. Also on your class Note there is no ForeignKey that links this note with the object (Car). Without this, the note doesn't know where it's being left on, just who wrote it, what was written, and when it was written. Mar 1, 2013 at 20:41
  • return "{1} created note on: {0}".format(self.created_on, self.user.name) Mar 1, 2013 at 20:42
  • That's the thing though, I am using the note functionality for a User model, but the admin is not logged in as that User. So Car = User and now I want one where Author = logged in User. Am i being clear enough?
    – Chris
    Mar 1, 2013 at 20:44
  • I've edited my answer below. Short answer is you cannot limit that field to the currently logged in user without a lot of tweaking with how the admin panel works, you'd need to write another view and supply the forms yourself. Not impossible, but more work than might be needed/desired. Mar 1, 2013 at 21:00

5 Answers 5

3

I know this is an old post, but just in case someone reached here, here's my solution, inspired by Django: How to get current user in admin forms:

models.py:

class Comment(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey("content_type", "object_id")
    user = models.ForeignKey(User)
    content = models.TextField()
    time = models.DateTimeField(auto_now_add=True)

admin.py:

class CommentInlineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(CommentInlineForm, self).__init__(*args, **kwargs)
        instance = getattr(self, 'instance', None)
        if instance and instance.pk:
            self.fields['content'].widget.attrs['readonly'] = True


class CommentInlineFormset(BaseGenericInlineFormSet):
    def save_new(self, form, commit=True):
        setattr(form.instance, "user", self.current_user)
        return super(CommentInlineFormset, self).save_new(
            form, commit=True)


class CommentInline(GenericTabularInline):
    model = Comment
    extra = 1
    form = CommentInlineForm
    formset = CommentInlineFormset
    readonly_fields = ('user', 'time')

    def has_delete_permission(self, request, obj=None):
        return False

    def get_formset(self, request, obj=None, **kwargs):
        formset = super(CommentInline, self).get_formset(
            request, obj, **kwargs)
        formset.current_user = request.user
        return formset

Note 1: The key here is to overwrite GenericTabularInline.get_formset() to pass in request.user, and use it to populate the "user" field in BaseGenericInlineFormSet.save_new(). So that the logged in user is recorded correctly. The other code are just there to make it more "comment" like. E.g, read only fields, no deletion, etc.

Note 2: This is a generic solution, so no matter which model we want to comment on, just add

inlines = [CommentInline,]

to the admin class and we are good to go.

2

I don't know what you mean by "overriding the entire view", because this kind of thing is what makes Django so nifty to use, the ability to bolt on extra functionality without too much fuss. Assuming that I'm not about to put my entire foot into my mouth, this is how I would approach it:

Adding notes to something shouldn't be overly difficult, just define another model within your cars.models and add something like Notes. Then just have this model reference the Cars model as it's foreign key and zippozappo - you've got yourself some notes.

As for "restricting" it to only admin, unless your public views will let people add notes or display the notes, it shouldn't ever appear outside of the admin application.

site/models.py

from django.contrib.auth.models import User
# snip your stuff...
class Notes(models.Model)
    user = models.ForeignKey('auth.User')
    author = models.ForeinKey('auth.User')
    note = models.TextField()
    created_on = models.DateTimeField(auto_now_add=True)

make sure to ./manage syncdb after this!

site/admin.py

from site.models import Notes
from django.contrib.auth.models import User

class NotesInline(admin.StackedInline):
    model = Notes
    extra = 0

class UserAdmin(UserAdmin):
    inlines = [NotesInline,]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

Here are some notes for using inline admin stuff, in case you wanted to customize the display of the notes at the end of each Car: https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.inlines

Of course you can expand/change/alter this how you like, but you shouldn't have to do anything tricky to add some additional functionality to your models.

Ideally you'd create a Notes app, that would let you comment on whatever object you wish, not just Users.

edit

class NotesInline now has a extra=0. This will stop 3 records showing up by default on the user page.

class Notes has an author = models.ForeinKey('auth.User') on it, which you need to keep track of who left the note in the first place. This will add a dropdown box that will let you select who is leaving the note. If I'm understanding correctly, you'd like to have this field auto-filled out by the currently logged-in user. The problem with forcing this is while on the admin panel, all admins are created equally (unless limited by permissions), so to limit this author field to the currently logged-in user will require more tinkering than you should bother with.

If you need to extend the admin panel to the point where you'd like to auto-fill out these fields, you will have to create some other public view, and then restrict access to those users who have permissions to access it. Either than or you will have to start overriding the admin views/templates yourself. This is kind of a by-design feature of Django's admin panel - it should be used for modifying your tables, not necessarily being the end-all user-input panel.

one more headache: Django's syncdb will not alter tables that already exist, so if you want to add/remove a column from an existing model, you need to drop and recreate the table, or use something like django-evolution. Use of that is for another question however.

1
  • This is probably the way to go. Although I still don't have it completely figured out. I will update my original question with some more information on my progress.
    – Chris
    Mar 1, 2013 at 20:16
2

This is an old question, but I made a package heavily inspired by Dryice Liu's work in his answer.

The package is called django-admin-comments. It's pretty easy to set up:

Install Django Admin Comments:

$ pip install django-admin-comments

Add it to your INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'admin_comments',
    ...
)

Run database migrations

$ manage.py migrate

Now, simply add the CommentInline to any ModelAdmin

from admin_comments.admin import CommentInline

class MyModelAdmin(admin.ModelAdmin):
    model = MyModel
    inlines = [CommentInline,]

That's it!

Pull requests welcome, and if anyone on this thread would like to become a contributor just open a PR adding yourself to the contributors list and I'll accept and add you.

2

For notes, you can now add a help text:

date = models.DateTimeField('date', help_text="This is a help text")
-1

Without digging into the admin, the easiest way would be to inject a comment form into the admin interfaces with javascript. You'd need to create a model to store the comments (you might be able to use the built in comments system, though that might be more trouble than its worth), some ajax for retrieving and saving comments, and a javascript widget that would render the retrieved comments and a commenting form.

Then you'd just need to include a reference to the script in the admin templates and not have to touch any of the admins internals.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.