3

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.

2
  • Is it a Django command (i.e. something you'd run via manage.py) or a standalone script? Commented Jun 27, 2017 at 20:05
  • It's made using Django commands, it can be run easily through manage.py, that's how I tested if it worked with the database. Commented Jun 27, 2017 at 20:08

1 Answer 1

4

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. :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.