Skip to content

make it work with django 1.11 #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
*.pyc
*~
example/db.sqlite
example/db.sqlite
django_admincommand.egg-info
.ropeproject
build/
dist/
3 changes: 3 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
include README.rst

recursive-include admincommand/templates *
4 changes: 3 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Then you will have to create a configuration class for the command::

# ./music/admincommands.py

from admincommands.models import AdminCommand
from admincommand.models import AdminCommand


class Lyrics(AdminCommand):
Expand All @@ -57,6 +57,8 @@ Then you will have to create a configuration class for the command::
def get_command_arguments(self, forms_data):
return [forms_data['title']], {}

*NOTE*: This all works based on naming conventions. The file with the form must be called `admincommands` and the form class name must be the same as the management command file name (with camel case converted to underscore notation).

And all is well, the new admin command will be available under the
«Admin Command» area of the administration of the default admin site.

Expand Down
23 changes: 10 additions & 13 deletions admincommand/admin.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
# -*- coding: utf-8 -*-
from functools import update_wrapper

from django.contrib import admin
from django.shortcuts import render
from django.contrib.admin.options import csrf_protect_m
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import redirect
from django.conf.urls.defaults import url
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.http import HttpResponseBadRequest
from django.conf.urls.defaults import patterns
from django.utils.encoding import force_unicode
from django.utils.functional import update_wrapper
from django.conf.urls import url
from django.utils.encoding import force_text
from django.http import HttpResponseForbidden
from django.utils.safestring import mark_safe
from django.contrib import messages
Expand All @@ -25,9 +23,9 @@
class AdminCommandAdmin(SneakAdmin):
list_display = ('command_name',)

def queryset(self, request):
def get_queryset(self, request):
# user current user to construct the queryset
# so that only commands the user can execute
# so that only commands the user can execute
# will be visible
return CommandQuerySet(request.user)

Expand All @@ -37,13 +35,12 @@ def wrapper(*args, **kwargs):
return self.admin_site.admin_view(view)(*args, **kwargs)
return update_wrapper(wrapper, view)

urlpatterns = patterns(
'',
urlpatterns = [
url(
r'^run/([\w_]+)',
wrap(self.run_command_view),
)
)
]
return urlpatterns + super(AdminCommandAdmin, self).get_urls()

def run_command_view(self, request, url_name):
Expand All @@ -60,7 +57,7 @@ def run_command_view(self, request, url_name):

ctx = {
# original needed ``change_form.html`` context variables
'module_name': force_unicode(opts.verbose_name_plural),
'module_name': force_text(opts.verbose_name_plural),
'title': admin_command.name(),
'is_popup': False,
'root_path': None,
Expand Down
17 changes: 12 additions & 5 deletions admincommand/core.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
from StringIO import StringIO
from six import StringIO

from importlib import import_module

from django.conf import settings
from django.core import management
from django.core.management import get_commands
from django.core.management import load_command_class
from django.utils.importlib import import_module
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from async import schedule
try:
from async import schedule
except ImportError:
schedule = None

from admincommand.models import AdminCommand


# Cache variable to store runnable commands configuration
# Cache variable to store runnable commands configuration
_command_configs = {}


Expand Down Expand Up @@ -57,12 +61,15 @@ def call_command(command_name, user_pk, args=None, kwargs=None):
management.call_command(command_name, *args, **kwargs)
return output.getvalue()


def run_command(command_config, cleaned_data, user):
if hasattr(command_config, 'get_command_arguments'):
args, kwargs = command_config.get_command_arguments(cleaned_data)
args, kwargs = command_config.get_command_arguments(cleaned_data, user)
else:
args, kwargs = list(), dict()
if command_config.asynchronous:
if not callable(schedule):
return 'This task is asynchronous but django-async is not installed'
task = schedule(call_command, [command_config.command_name(), user.pk, args, kwargs])
return task
else:
Expand Down
10 changes: 8 additions & 2 deletions admincommand/management.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from importlib import import_module

import django
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.db.models import signals
from django.utils.importlib import import_module

import admincommand

Expand Down Expand Up @@ -31,4 +33,8 @@ def sync_db_callback(verbosity=0, interactive=False, signal=None, **kwargs):
content_type=ct,
name='Can run %s' % subclass.command_name(),
)
signals.post_syncdb.connect(sync_db_callback, sender=admincommand.models)

if django.VERSION >= (1, 7):
signals.post_migrate.connect(sync_db_callback, sender=admincommand.models)
else:
signals.post_syncdb.connect(sync_db_callback, sender=admincommand.models)
22 changes: 22 additions & 0 deletions admincommand/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations


class Migration(migrations.Migration):

dependencies = [
]

operations = [
migrations.CreateModel(
name='AdminCommand',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
],
options={
'abstract': False,
},
),
]
File renamed without changes.
4 changes: 2 additions & 2 deletions admincommand/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def get_help(self):

def command(self):
"""Getter of the management command import core"""
import core
from . import core
command = core.get_command(self.command_name())
return command

Expand All @@ -53,6 +53,6 @@ def permission_codename(cls):

@classmethod
def all(cls):
import core
from . import core
for runnable_command in core.get_admin_commands().values():
yield runnable_command
6 changes: 1 addition & 5 deletions admincommand/templates/admincommand/output.html
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
{% extends "admin/change_form.html" %}

{% load i18n %}

{% block extrahead %}
{{ block.super }}
<script type="text/javascript" src="{{ STATIC_URL }}libe/js/jquery.js"></script>
{% endblock %}
{% load i18n %}

{% block breadcrumbs %}
<div class="breadcrumbs">
Expand Down
2 changes: 1 addition & 1 deletion admincommand/templates/admincommand/run.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,6 @@
<p>{{ help }}</p>
<form method="POST">{% csrf_token %}
{{ form.as_ul }}
<input type="submit" value="Lancer"/>
<input type="submit" value="Run"/>
</form>
{% endblock %}
1 change: 0 additions & 1 deletion example/admincommand

This file was deleted.

Empty file added example/example/__init__.py
Empty file.
123 changes: 123 additions & 0 deletions example/example/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
"""
Django settings for example project.

Generated by 'django-admin startproject' using Django 1.11.3.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '!5os-5fccaf-c)c#&&(z1h@=n9i@!jbm4k*f^3$9ps&%fc9fga'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'admincommand',
'exampleapp',
'async',
]

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'example.urls'

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

WSGI_APPLICATION = 'example.wsgi.application'


# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}


# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]


# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/

STATIC_URL = '/static/'
21 changes: 21 additions & 0 deletions example/example/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""example URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', admin.site.urls),
]
16 changes: 16 additions & 0 deletions example/example/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
WSGI config for example project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "example.settings")

application = get_wsgi_application()
3 changes: 3 additions & 0 deletions example/exampleapp/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin

# Register your models here.
Loading