code Django git python

Django management commands from admin interface

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:

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 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 = AdminSitePlus()

Now, head to the 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):'import_movies_from_url', 'Import Movies from URL')
    def import_movies_from_url(request):
        print('import movies here')
            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'), 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.

Screen Shot 2017-10-26 at 1.36.02 PM

More details on admin_plus

Again, here is the github repo with all the import scripts and sample files:
Happy coding ๐Ÿ™‚

Leave a Reply

Your email address will not be published. Required fields are marked *