2

Suppose I have a model like this:

class Foo(models.Model):
    name = models.CharField(max_length=50)
    year = models.IntegerField(max_length=4)
    some_value = models.IntegerField(default=0)

and

class Bar(models.Model)
    name = models.CharField(max_length=50)
    foo = models.ForeignKey(Foo)

Then I register my models in django AdminSite using FooAdmin class:

class FooAdmin(admin.ModelAdmin):
    list_display = ['name', 'year', 'some_value']

It works fine, but for some reason I need to add two buttons for each Foo row in my admin site. Let's say I'd call them 'Related_button' and 'Action_button'

I need those buttons to be in each row and to behave as follows:
-when user clicks on 'Related_button', he is redirected to django admin site where all Bars related with particullar Foo object are listed
-when user clicks on 'Action_button', a field some_value in object of class Foo is set to a custom value, let's say 15. But before that, confirm popup (Are you sure? y/n) should appear.

How to do that? I figured out that I could do something like:

def button(self, obj):
    return '''<input type="button" value="button" />'''
button.short_description = 'Action'
button.allow_tags = True
list_display = ['name', 'year', 'some_value', 'action']

in my FooAdmin which causes a button to appear in each row. But how can I set an action for that button?

2 Answers 2

6

The list page is a form.

<form id="changelist-form" action="" method="post">

Adding buttons to it will submit the form. To do something with the formdata you have to create a custom admin form. It will be dirty because it's a fromset containing all displayed rows, and not just your single row. I guess it can be done, but there are better ways:

Most of the time Admin Actions will do just fine. Admin actions look like this:

Admin actions

def rename_action(modeladmin, request, queryset):
    queryset.update(name='Ni')
make_published.short_description = "Rename selected objects to 'Ni'"

class FooAdmin(admin.ModelAdmin):
    actions = [rename_action, ...]

But if you want more flexibility than an Admin Action, feel free to write custom views for the admin. The admin is powered by Django itself, and you can write custom views that hook into the authentication system, check permissions and do whatever else they need to do. It goes like this:

class Foo(models.Model):
    ...

    def my_action_link(self, obj):
        return '<a href="/admin/app/foo/my_custom_action/%d/" class="link">Action name</a>' %obj.id
    my_action_link.short_description = 'My action'
    my_action_link.allow_tags = True

Now my action is a link that points to some custom url and custom admin view. Create a custom admin view:

class FooAdmin(admin.ModelAdmin):
    ...

    list_display = ['name', 'my_action_link', ...]

    def get_urls(self):
        urls = super(FooAdmin, self).get_urls()
        my_urls = patterns('',
            (r'^my_custom_action/(?P<pk>\d+)/$', self.my_view)
        )
        return my_urls + urls

    @permission_required('foo.can_change')
    def my_view(self, request):
        obj = get_object_or_404(Foo, pk=pk)
        obj.do_something()
        # Redirect back to the change list. Or something else?
        # You could add some modelform to this view. :)

I didn't test this code. But I hope you get the idea. Happy hacking!

[EDITED]: Linked reference Django 1.6 URLs not working anymore. Added Django 1.11 URLs

7
  • Thank you, that loooks great! But I'm worried about one thing - I have also modified queryset mehtod in my FooAdmin as follows : return Foo.objects.filter(created_by=request.user). Is my_view looking for Foo object in my filtered set or is it retrieving it directly from database? I don't want to let my user see things he's not allowed to.
    – slnowak
    Dec 14, 2013 at 20:57
  • I guess your user could be fiddling with the url. But you could do: obj = get_object_or_404(Foo, pk=pk, created_by=request.user) if a obj isn't created by that user it'll raise a 404.
    – allcaps
    Dec 14, 2013 at 22:32
  • Or course there are other ways. Check and return a useful message: if request.user != obj.created_by: return "This incident will be reported."
    – allcaps
    Dec 14, 2013 at 22:36
  • To answer your comment question: This is a regular view and will query the db. It has nothing to do with the admin qs method.
    – allcaps
    Dec 14, 2013 at 22:41
  • Thanks. And one last question : is it possible to change django admin actions so that they work as a buttons instead of that menu you showed above?
    – slnowak
    Dec 14, 2013 at 22:55
-1

Add custom js to admin class:

class FooAdmin(admin.ModelAdmin):
    list_display = ['name', 'year', 'some_value']

    class Media:
        js = ("/media/javascript/yourjs.js",)
1
  • Could you write something more? Unfortunately, I don't know java script. And which one of my problems should it solve?
    – slnowak
    Dec 14, 2013 at 18:44

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.