This need came up when during app deployment, needed to run some management commands without ssh-ing into the server or using the terminal.
Thankfully Django management command can be called anywhere using management.call_command()
This is a brief one, view code on GitHub here:
https://github.com/NEbere/data-import/tree/master
You need to install the admin_plus package with pip, ensure your virtual environment is setup and activated if that’s what you’re using, in any case, ensure you have the right environment setup and running for your app before installing to avoid any issues ๐
Install admin_plus:
pip install django-adminplus
Add adminplus to INSTALLED_APPS in your settings file
If youโre using Django 1.7, you should also replace django.contrib.admin with django.contrib.admin.apps.SimpleAdminConfig in your installed apps, in order to disable the automatic auto-discovery:
so update ‘django.contrib.admin’ to ‘django.contrib.admin.apps.SimpleAdminConfig’ in INSTALLED_APPS in your settings file
import AdminSitePlus in urls.py of your main package, the file where URL’s from installed apps are registered
hint: this is where you have the admin URL defined
In that same file, add this for the admin_plus
admin.site = AdminSitePlus() admin.autodiscover()
Now, head to the admin.py file in your app and call the command you want to execute.
from django.contrib import admin from .models import Movie from django.core import management from django.shortcuts import redirect class MovieAdmin(admin.ModelAdmin): @admin.site.register_view('import_movies_from_url', 'Import Movies from URL') def import_movies_from_url(request): print('import movies here') try: management.call_command('import_from_url') message = 'successfully imported data from URL' except Exception as ex: message = 'Error importing from data from URL {}'.format(str(ex)) admin.ModelAdmin.message_user(Movie, request, message) return redirect('admin:index') admin.site.register(Movie, MovieAdmin)
the command I am calling here is import_from_url and that name corresponds to the file where I defined the command (minus the file .py file extension)
This does two things:
1. Makes your Model available on the admin interface, you can create, update, delete models objects from the admin interface once your models are registered.
2. Provides a link that when clicked runs the management command defined to be run.
More details on admin_plus
Again, here is the github repo with all the import scripts and sample files:
https://github.com/NEbere/data-import/blob/call-management-command-from-admin/
Happy coding ๐