开发者

How to have a grid with buttons in the Django admin and and pass the button a record id?

Easiest sai开发者_StackOverflow社区d with pictures.

How to have a grid with buttons in the Django admin and and pass the button a record id?

I'm not sure how to create the 2nd column with the button. Then how to add an id so that the button runs code for the specific record.


Although I think actions are better, if you really need a button, here's the easiest way:

Define a function that returns an HTML button in your model. How a view handles that button action is your call and just like any other view.

One idea is to link to a specific URL like /restart/3/ (if this button is performing a safe operation) or put form elements in each button that POSTs to a separate view with <input type="hidden" name="id" value="%(the_id)s" />

# models.py
    def restart_button(self):
        return '<a href="restart/%s">Restart Me</a>' % (self.id) 
    restart_button.allow_tags = True

# admin.py
list_display = ('restart_button', ...)

def get_urls(self):
    # use get_urls for easy adding of views to the admin
    urls = super(MyModelAdmin, self).get_urls()
    my_urls = patterns('',
        (r'^restart/(?P<id>\d)$', self.restart)
    )
    return my_urls + urls

def restart(self, request, id):
    MyModel.objects.get(id=id).restart()
    request.user.message_set.create(message="%s restarted." % id)
    return http.HttpResponseRedirect('../')


Adding a button is going to be a relatively large amount of work compared to the recommended solution to this kind of thing: adding an admin action, which will let you tick the object(s) you want to act on, then choose what to do from the Action: drop-down.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜