Reputation: 43
I have a python script written that takes an input from one model, queries it, and appends the various results from the query to another model through a ForeignKey relationship. It works great from the python shell, but I was wondering if there is a way to run it from the admin webpage so that every time a new object for the first model is submitted, it runs the script and updates the database automatically for the other model. I'm using the Django admin interface as part of development for staff to do data entry since I've found it's a very flexible interface. The script is written specifically for this app, so it is on the app's folder.
Upvotes: 3
Views: 2435
Reputation: 3178
I was surprised that this wasn't already answered.
Either wrap the existing script as a management command, or import it into a management command.
Once you've done that, you can override the Admin view in question, like this..
from django.contrib.admin import AdminSite
from django.views.decorators.cache import never_cache
class MyAdminSite(AdminSite):
@never_cache
def index(self, request, extra_context=None):
# do stuff
Then, you create an instance of this class, and use this instance, rather than admin.site to register your models.
admin_site = MyAdminSite()
Then, later:
from somewhere import admin_site
class MyModelAdmin(ModelAdmin):
...
admin_site.register(MyModel, MyModelAdmin)
Lastly, in that overriding view, you can use management.call_command
from your code to call the management command. This lets you use it both from the commandline, and from inside your code - and if you need to, you can schedule it from cron, too. :)
Upvotes: 4