I have created an app in a django project. This app has four models. I can add/modify/delete from admin site for all four models. But for one of the four models (say - ModelXYZ), I need to add a custom button for each entry in this table. Currently, I can see "Save", "Delete", etc. buttons for each entry present in ModelXYZ table. I need to add another button "Run", clicking on it will execute a python script written in that app only. Currently, I am running that script like this -
python manage.py shell
>>> execfile("my_app/my_script_1.py")
>>> execfile("my_app/my_script_2.py")
The script name is also stored in ModelXYZ table for each entry.
Django docs say that the admin site is customizable, but I am not very sure how can I run a python script by clicking on a button.
I solved it like this and it solves my purpose :-
class Site(models.Model):
name = models.CharField(null=False, blank=False, max_length=256, unique=True)
script = models.CharField(null=False, blank=False, max_length=256)
def __unicode__(self):
return u"{0}".format(self.name)
Then in my_app/admin.py, I wrote:-
from django.contrib import admin
from .models import *
def run(self, request, queryset):
id=request.POST.get('_selected_action')
siteObj=self.model.objects.get(pk=id)
self.message_user(request, "Running: " + siteObj.script)
execfile(siteObj.script)
run.short_description = "Run the script"
class SiteAdmin(admin.ModelAdmin):
actions = [run]
model = Site
# Register your models here.
admin.site.register(Site, SiteAdmin)