django-extensions

repository·main·Indexed 27 days ago

https://github.com/django-extensions/django-extensions

A collection of custom extensions for the Django Framework designed to improve the developer experience. It provides enhanced CLI commands and utilities, including an admin interface generator (admin_generator), bytecode management (clean_pyc, compile_pyc), cache clearing (clear_cache), and advanced model import collision resolvers for Shell Plus.

Tokens
33.7K
Snippets
79
Records
266
Agent score
89%

What's inside django-extensions

  1. Explore Django Extensions Command List

    main

    Django Extensions provides a wide array of management commands to enhance your Django development workflow. These include tools for database management, model visualization, shell enhancements, and server utilities.

    Key categories of commands include:

    • Development Utilities: shell_plus, runserver_plus, generate_secret_key, describe_form.
    • Database & Migrations: reset_db, reset_schema, sqldiff, sqlcreate, sqldsn, syncdata, delete_squashed_migrations.
    • Model & Data Management: graph_models, list_model_info, merge_model_instances, dumpscript.
    • Template & File Utilities: validate_templates, find_template, show_template_tags, unreferenced_files.
    • System & Debugging: mail_debug, print_settings, runscript, notes.
  2. Create a job script

    main

    A job is a Python script containing a class named Job. This class must inherit from one of the following base classes depending on the desired frequency:

    • MinutelyJob (requires a minutely directory)
    • QuarterHourlyJob (requires a quarter_hourly directory)
    • HourlyJob (requires an hourly directory)
    • DailyJob (requires a daily directory)
    • WeeklyJob (requires a weekly directory)
    • MonthlyJob (requires a monthly directory)
    • YearlyJob (requires a yearly directory)

    Each job class must implement the execute method, which contains the logic to be run.

  3. Use ModelUserFieldPermissionMixin to restrict view access by owner

    main

    The ModelUserFieldPermissionMixin is a Class Based View (CBV) mixin that limits access to a view based on the ownership of a model instance. It verifies that the currently logged-in user (self.request.user) matches the user assigned to a specific field on the model instance.

    By default, the mixin expects the owner field to be named user. If your model uses a different field name (e.g., author), you must specify it using the model_permission_user_field attribute on the view class.

    # models.py
    from django.db import models
    from django.conf import settings
    
    class MyModel(models.Model):
       author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
       content = models.TextField()
    
    
    # views.py
    from django.views.generic import UpdateView
    from django_extensions.auth.mixins import ModelUserFieldPermissionMixin
    from .models import MyModel
    
    class MyModelUpdateView(ModelUserFieldPermissionMixin, UpdateView):
        model = MyModel
        template_name = 'mymodels/update.html'
        # Specify the field on MyModel that identifies the owner
        model_permission_user_field = 'author'
  4. Reset an app and reload data using dumpscript

    main

    To completely reset an application's data and reload it from a previously generated dumpscript, use the reset command followed by runscript.

    Note: For runscript to work, the directory containing your scripts must be a Python module. You must create the directory and include an __init__.py file within it.

    ./manage.py reset appname
    ./manage.py runscript testdata
  5. Generate a standalone Python script with dumpscript

    main
    The dumpscript command generates a standalone Python script that can be used to repopulate a database using Django objects. This approach is more flexible than XML or direct SQL because it handles model evolution (like foreign keys and column changes) naturally and allows you to programmatically edit the script (e.g., using loops to generate thousands of entries).
  6. Use sqlcreate to automate database setup

    main

    The sqlcreate command helps you automate the creation of your database(s) by using the configuration already defined in your settings.py. Instead of creating databases manually, you can generate the necessary SQL and pipe it directly into your database's shell command.

    Usage Pattern: python manage.py sqlcreate [--database=<databasename>] | <my_database_shell_command>

    Note on Permissions: sqlcreate generates the SQL for you to review and pipe into a shell. It does not execute the commands directly because it cannot guarantee the database user in your settings has the necessary administrative permissions to create databases and users.

    python manage.py sqlcreate [--database=<databasename>] | <my_database_shell_command>
  7. Use debugger filters in Django templates

    main

    You can trigger interactive debugger sessions (using ipdb, pdb, or wdb) directly within Django templates by using the debugger_tags template tags. This allows you to inspect objects and variables during the template rendering process.

    1. Load the tags in your template using {% load debugger_tags %}.
    2. Apply a debugger filter to the object or variable you wish to inspect (e.g., {{ variable|ipdb }}).

    Supported filters:

    • ipdb
    • pdb
    • wdb
    {% load debugger_tags %}
    
    {% for object in object_list %}
        {{ object|ipdb }}
    {% endfor %}
  8. Apply app-based styling to graph models

    main

    You can visually distinguish models by app using a JSON styling file. The file maps app labels (supporting wildcards like django.*) to style dictionaries. Currently, only the bg (background color) option is supported.

    Styling Workflow:

    1. Create a JSON file (e.g., style.json).
    2. Place it in the project root (named .app-style.json) OR specify it via the --app-style flag.
    3. Run the command with the -o flag to output an image.

    JSON Format Example:

    {
      "app1": {"bg": "#341b56"},
      "app2": {"bg": "#1b3956"},
      "django.*": {"bg": "#561b4c"},
      "django.contrib.auth": {"bg": "#c41e3a"}
    }
    $ ./manage.py graph_models -a --app-style path/to/style.json -o styled_output.png
  9. Run the development server with runserver_plus

    main

    Use runserver_plus instead of the standard Django runserver to launch a development server with the Werkzeug debugger integrated. This provides interactive tracebacks, source code viewing, and an AJAX-based debugging console. All standard runserver options (like port and host) are supported.

    Requirement: You must have Werkzeug installed.

    python manage.py runserver_plus
  10. Configure Werkzeug logging in Django

    main

    To ensure Werkzeug logs appear in your console, add the following to your Django LOGGING configuration:

    LOGGING = {
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'werkzeug': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }
    LOGGING = {
        'handlers': {
            'console': {
                'level': 'DEBUG',
                'class': 'logging.StreamHandler',
            },
        },
        'loggers': {
            'werkzeug': {
                'handlers': ['console'],
                'level': 'DEBUG',
                'propagate': True,
            },
        },
    }