Write Django management command using the click CLI library

Overview

Django Click

Project information:

Automated code metrics:

django-click is a library to easily write Django management commands using the click command line library.

  • Free software: MIT license
  • Documentation for the Click command line library: http://click.pocoo.org/7/
  • Compatible with Django 2.2 or 3.0 running on Python 3.6, 3.7, 3.8, and PyPy.

Installation

pip install django-click

Example

Create a command module as you would usually do, but instead of creating a class, just put a djclick command into <yourapp>/management/commands/helloworld.py:

import djclick as click

@click.command()
@click.argument('name')
def command(name):
    click.secho('Hello, {}'.format(name), fg='red')

And then call the command with:

$ ./manage.py helloworld django-click
Hello, django-click

Check out the test commands for additional example commands and advanced usage.

Comments
  • Django-click doesn't work with click >= 7.1

    Django-click doesn't work with click >= 7.1

    When installing a version of click later than 7.0, the djclick import fails with an error:

        import djclick
    /usr/local/lib/python3.6/site-packages/djclick/__init__.py:16: in <module>
        __all__ = click.__all__ + ['pass_verbosity']
    E   AttributeError: module 'click' has no attribute '__all__'
    

    The click module does not define __all__ as of 7.1 and later.

    opened by ykshatroff 5
  • click.exceptions.MissingParameter: None

    click.exceptions.MissingParameter: None

    click==6.6, django-click==1.2.0, django==1.5.12

    If the one required parameter is omitted from the following management command, the user sees the error message in the subject of this issue

    import djclick as click
    
    @click.command()
    @click.argument('name')
    def command(name):
       click.secho('Hello, {}'.format(name), fg='red')
    

    If the one required parameter is omitted from the following command, the user sees a better error message.

    import click
    
    @click.command()
    @click.argument('name')
    def hello(name):
        click.secho('Hello, {}'.format(name), fg='red')
    
    if __name__ == '__main__':
        hello()
    
    $ python foo.py 
    Usage: foo.py [OPTIONS] NAME
    
    Error: Missing argument "name".
    

    Any ideas? This would seem to be a django-click issue?

    opened by trawick 3
  • Allow other lookups in `ModelInstance`

    Allow other lookups in `ModelInstance`

    Currently ModelInstance allows lookups only by pk. This PR adds support for arbitrary lookups by adding a lookup keyword argument.

    Example:

    @clik.option('--something', type=ModelInstance(SomeModel, lookup='name'))
    

    (This PR is intended to be merged on top of the changes from #2 )

    opened by ulope 3
  • Use commands.py instead of management/commands/each_one.py

    Use commands.py instead of management/commands/each_one.py

    This will allow getting rid of this rediculous deep directory structure and lots of files. It should be still possible to split commands into several files, but python way:

    commands/
        __init__.py
        command1.py
        command2.py
        filecommands.py
        utils.py
    

    with commands/__init__.py:

    from .command1 import Command1
    from .command2 import Command2
    from .filecommands import *
    

    Different splitting srategies are possible this way: single file for command or file for some logical command group or just no splitting. Also this resembles how models.py was split.

    wontfix 
    opened by Suor 3
  • Click 7.1 breaks django-click

    Click 7.1 breaks django-click

    click 7.1 dropped a few hours ago, and out of the box, creates errors with django-click:

    module 'click' has no attribute '__all__'

    This will keep deployments from breaking in the meantime.

    opened by FlipperPA 2
  • Port `.travis.yml` to GitHub Actions

    Port `.travis.yml` to GitHub Actions

    This PR closes #34.

    Ports the existing .travis.yml file over to GitHub Actions with full feature parity.

    Passing tests from last commit.

    Coveralls upload step is commented out since I do not have access to that external system and I wanted to show all green across the board for the passing tests.

    opened by joshuadavidthomas 1
  • Click 8 is a rejected dependency

    Click 8 is a rejected dependency

    A couple of days ago, Click 8 was released. I've since tried using this with a project that has a dependency on Click 8, which led to some invalid dependency resolution due to the fact that django-click specifies a strict upper bound smaller than 7.2. Is there any reason why that limit is enforced, or can it be removed? Alternatively, is there more work that's needed to check that it runs with Click 8 and enable that?

    opened by DragosDumitrache 1
  • Fix issues with recent versions of click and django

    Fix issues with recent versions of click and django

    Fix multiple issues with recent versions of click and Django:

    • Django 3 removes Python 2 compatibility shims, like python_2_unicode_compatible; use the one from six instead
    • Django 3 handles ArgumentParser's mutually exclusive groups; add the attribute to ArgumentParserAdapt to make Django happy
    • Recent versions of click do not exit on ctx.exit() if standalone_mode = False, instead returning the exit code from Command.main(); use that exit code and exit "manually" instead, if it's non-zero
    • Different versions of click cases metavars differently; lowercase some output in tests to make checking equality more compatible with multiple click versions
    • Different versions of pytest stringifies ExceptionInfo differently; match against exception message in tests instead of checking against how pytest formats its wrapper
    • Fix help and usage output to show command names correctly; specifically, don't show the base command name twice, and show it (once) when showing usage for sub-commands (Fixes #8)
    • Style CommandError like Django, with red, bold text
    opened by simonpercivall 1
  • Bumped django/python versions to test against.

    Bumped django/python versions to test against.

    Also made tox/travis configs easier to maintain by simply listing all python/django mixes separately.

    Am doing that as currently package looks like abandonware. Once everything passes I'd update other files/bump package version.

    opened by lukaszb 1
  • Update tests

    Update tests

    Various test updates. In detail:

    • Test on Python 3.5 and Django 1.9
    • Rename pypy19 tox env to pypy since pypy19 is not recognized by tox as pypy and caused the tests to run on cpython 2.7 instead
    • Fixes some failing Python 3 tests
    • Add coverage terminal reporting output
    • Add pytest-django. This allows to use real models in test_params instead of the DummyQuerySet
    opened by ulope 1
  • Move from Travis CI to Github Actions for CI

    Move from Travis CI to Github Actions for CI

    Since June earlier this year, Travis CI no longer supports free open source CI. If you look at the Travis builds, you can see they haven't been running since then.

    Github Actions has become the defacto standard for CI for open source projects. This repository offers a good template for using a testing matrix against all the different versions of Python & Django this package needs to support.

    opened by joshuadavidthomas 0
  • Raising Abort Causes Stacktrace Instead of Clean Shutdown.

    Raising Abort Causes Stacktrace Instead of Clean Shutdown.

    When either sending a SIGINT or using raise click.Abort, I would expect the application to shut down cleanly with the appropriate error code. Instead, I get the following stack trace:

    Traceback (most recent call last):
      File "./manage.py", line 24, in <module>
        execute_from_command_line(sys.argv)
      File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
        utility.execute()
      File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/usr/local/lib/python3.8/site-packages/djclick/adapter.py", line 68, in run_from_argv
        exit_code = self.main(
      File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1055, in main
        rv = self.invoke(ctx)
      File "/usr/local/lib/python3.8/site-packages/djclick/adapter.py", line 50, in invoke
        return super(DjangoCommandMixin, self).invoke(ctx)
      File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1657, in invoke
        return _process_result(sub_ctx.command.invoke(sub_ctx))
      File "/usr/local/lib/python3.8/site-packages/click/core.py", line 1404, in invoke
        return ctx.invoke(self.callback, **ctx.params)
      File "/usr/local/lib/python3.8/site-packages/click/core.py", line 760, in invoke
        return __callback(*args, **kwargs)
      File "/srv/service/vite_frontend/management/commands/frontend.py", line 157, in dev
        f.write(f"{app.name}\n{process.pid}\n")
      File "/usr/local/lib/python3.8/contextlib.py", line 120, in __exit__
        next(self.gen)
      File "/srv/service/vite_frontend/management/commands/frontend.py", line 70, in run_vite
        yield process
      File "/usr/local/lib/python3.8/contextlib.py", line 120, in __exit__
        next(self.gen)
      File "/srv/service/vite_frontend/management/commands/frontend.py", line 47, in run_in_app
        raise click.Abort()
    

    We have worked around this by instead throwing a SystemExit exception, but it would be nice to be able to use Abort

    opened by peacememories 0
  • Add typing annotations

    Add typing annotations

    Hi and thanks for maintaining this convenient library. It really makes our management commands look a lot cleaner. What's missing for us at the moment, though, is typing annotations, since we're running mypy on all of our code.

    Right now we're working around this by creating a stub for mypy to use, but it would obviously be much better to have first party type annotations. Is this something that's planned/you're interested in adding?

    Thanks for considering :)

    opened by peacememories 2
  • Typer Integration

    Typer Integration

    I am usually using Typer on top of Click for command line. This gives a nice way to use Type hints to define variables. https://typer.tiangolo.com

    How complex do you think it would be to have a Typer adopter for django-click?

    opened by Benoss 4
  • stdout does not work on `call_command`

    stdout does not work on `call_command`

    Assuming we have a command named foo...

    import io
    
    buffer = io.StringIO()
    from django.core.management import call_command
    call_command("foo", stdout=buffer)
    out = buffer.getvalue()
    assert "whatever" in out
    

    This is not possible with django-click, instead saying:

    TypeError: Unknown option(s) for dumb command: stdout. Valid options are: color, h, help, pythonpath, settings, traceback, v, verbosity, version.
    

    Environment

    • Django 3.2.5
    • Python 3.8
    • Poetry 1.1.7
    • Pytest 6.2.4
    • Pytest Django 4.4.0
    • (if relevant) Ubuntu 20.04
    opened by erayerdin 0
  • Can't pass

    Can't pass "help" parameter to click argument

    The following script works with the base click library but raises an exception with the django-click library.

    import djclick as click
    
    @click.command()
    @click.argument("name", help="Some name")
    def command(name):
        click.echo(f"Hi {name}!")
    

    Exception:

    Traceback (most recent call last):
      File "/app/./manage.py", line 22, in <module>
        main()
      File "/app/./manage.py", line 18, in main
        execute_from_command_line(sys.argv)
      File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line
        utility.execute()
      File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 244, in fetch_command
        klass = load_command_class(app_name, subcommand)
      File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 37, in load_command_class
        module = import_module('%s.management.commands.%s' % (app_name, name))
      File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
      File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
      File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
      File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
      File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
      File "<frozen importlib._bootstrap_external>", line 790, in exec_module
      File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
      File "/app/core/management/commands/click1.py", line 6, in <module>
        def command(name):
      File "/usr/local/lib/python3.9/site-packages/click/decorators.py", line 168, in decorator
        _param_memo(f, ArgumentClass(param_decls, **attrs))
      File "/usr/local/lib/python3.9/site-packages/click/core.py", line 1984, in __init__
        Parameter.__init__(self, param_decls, required=required, **attrs)
    TypeError: __init__() got an unexpected keyword argument 'help'
    
    opened by johnnymetz 0
  • call_command replacement

    call_command replacement

    I'm trying to call a djclick based management command using the traditional Django API, django.core.management.call_command and I'm getting this traceback:

    Traceback (most recent call last):
      File "_log.py", line 34, in <module>
        call_command('sync_models')
      File "/home/user/.cache/pypoetry/virtualenvs/ht-ZBbfQ9hA-py3.8/lib/python3.8/site-packages/django/core/management/__init__.py", line 135, in call_command
        for group in parser._mutually_exclusive_groups
    AttributeError: 'ArgumentParserAdapter' object has no attribute '_mutually_exclusive_groups'
    

    I could do from myproject.myapp.management.commands.my_command import command although the command I'm using is the grouping feature.

    What would be the advised methodology to run the command in a programmatic fashion?

    opened by D3f0 1
Releases(2.3.0)
  • 2.3.0(Sep 7, 2021)

  • 2.2.0(Jul 20, 2020)

  • v2.1.1(Jun 12, 2020)

    This release will ensure the version of click is lower then 7.1 for compatibility.

    • Final release to support Python 2.7, 3.4 & 3.5.
    • Final release to support Django 1.11, 2.0 & 2.1.
    Source code(tar.gz)
    Source code(zip)
Owner
Jonathan Stoppani
Jonathan Stoppani
A cli tool , which shows you all the next possible words you can guess from in the game of Wordle.

wordle-helper A cli tool , which shows you all the next possible words you can guess from the Game Wordle. This repo has the code discussed in the You

1 Jan 17, 2022
Ntfy - 🖥️📱🔔 A utility for sending notifications, on demand and when commands finish.

About ntfy ntfy brings notification to your shell. It can automatically provide desktop notifications when long running commands finish or it can send

Daniel Schep 4.5k Jan 01, 2023
Pequeno joguinho pra você rodar no seu terminal

JokenPython Pequeno joguinho pra você rodar no seu terminal Olá! Joguinho legal pra vc rodar no seu terminal!! (rode no terminal, pra melhor experienc

Scott 4 Nov 25, 2021
This is an app for creating your own color scheme for Termux!

Termux Terminal Theme Creator [WIP] If you need help on how to use the program, you can either create a GitHub issue or join this temporary Discord se

asxlvm 3 Dec 31, 2022
Automated CI toolchain to produce precompiled opencv-python, opencv-python-headless, opencv-contrib-python and opencv-contrib-python-headless packages.

OpenCV on Wheels Pre-built CPU-only OpenCV packages for Python. Check the manual build section if you wish to compile the bindings from source to enab

OpenCV 3.2k Jan 04, 2023
AML Command Transfer. A lightweight tool to transfer any command line to Azure Machine Learning Services

AML Command Transfer (ACT) ACT is a lightweight tool to transfer any command from the local machine to AML or ITP, both of which are Azure Machine Lea

Microsoft 11 Aug 10, 2022
CLI tool to fix linked references for dates.

Fix Logseq dates This is a CLI tool to fix the date references following a change in date format since the current version (0.4.4) of Logseq does not

Isaac Dadzie 5 May 18, 2022
CLI for SQLite Databases with auto-completion and syntax highlighting

litecli Docs A command-line client for SQLite databases that has auto-completion and syntax highlighting. Installation If you already know how to inst

dbcli 1.8k Dec 31, 2022
GoSearch for anything from your terminal

GoSearch for anything from your terminal Requirements pip install beautifulsoup4

Malik Mouhiidine 1 Oct 02, 2021
A selfbot made with DPY, doesn't have much commands but there's some useful commands to use.

Phantom Selfbot A selfbot made in DPY, made by Zenith. How to use Add your token in token = 'YOUR-MOMS-TOKEN-HERE' Change the prefix in prefix = If

[Ͼ⁴] Ƶephyr 2 Dec 02, 2021
A python-based terminal application that displays current cryptocurrency prices

CryptoAssetPrices A python-based terminal application that displays current cryptocurrency prices. Covered Cryptocurrencies Bitcoin (BTC) Ethereum (ET

3 Apr 21, 2022
A terminal spreadsheet multitool for discovering and arranging data

VisiData v2.6.1 A terminal interface for exploring and arranging tabular data. VisiData supports tsv, csv, sqlite, json, xlsx (Excel), hdf5, and many

Saul Pwanson 6.2k Jan 04, 2023
A CLI tool that scans through a directory and organizes all loose files into folders by file type.

Organizer CLI Organizer CLI is a python command line tool that goes through a given directory and organizes all un-folder bound files into folders by

Mulaza Jacinto 6 Dec 14, 2022
Shortcut-Maker - It is a tool that can be set to run any tool with a single command

Shortcut-Maker It is a tool that can be set to run any tool with a single command Coded by Dave Smith(Owner of Sl Cyber Warriors) Command list 👇 pkg

Dave Smith 10 Sep 14, 2022
Standalone script written in Python 3 for generating Reverse Shell one liner snippets and handles the communication between target and client using custom Netcat binaries

Standalone script written in Python 3 for generating Reverse Shell one liner snippets and handles the communication between target and client using custom Netcat binaries. It automates the boring stu

Yash Bhardwaj 3 Sep 27, 2022
TerminalGV is a very simple client to display stats about your SNCF TGV/TER train in your terminal.

TerminalGV So I got bored in the train, TerminalGV is a very simple client to display stats about your SNCF TGV/TER train in your terminal. The "on-tr

Samuel 8 Dec 15, 2022
Unofficial Open Corporates CLI: OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unofficial open corporates python command line tool.

Unofficial Open Corporates CLI OpenCorporates is a website that shares data on corporations under the copyleft Open Database License. This is an unoff

Richard Mwewa 30 Sep 08, 2022
A command-line tool to flash python code to Codey Rocky without having to use the online mblock5 IDE.

What? A command-line tool to flash python code to Codey Rocky without having to use the online mblock5 IDE. Description This is a very low-effort proj

1 Dec 29, 2021
'rl_UK' is an open-source command-line tool in Python for calculating the shortest path between BUS stop sequences in the UK

'rl_UK' is an open-source command-line tool in Python for calculating the shortest path between BUS stop sequences in the UK. As input files, it uses an ATCO-CIF file and 'OS Open Roads' dataset from

Nesh P. 0 Feb 16, 2022
A CLI framework based on asyncio

asynccli A CLI framework based on asyncio. Note This is still in active development. Things will change. For now, the basic framework is operational.

Adam Hopkins 6 Nov 13, 2022