django-admin-easy

repository·main·Indexed 19 days ago

https://github.com/ebertti/django-admin-easy

A collection of tools, including fields, decorators, and mixins, designed to simplify the creation of computed, custom, or formatted fields within the Django Admin interface. It provides EasyAdminField classes for common tasks, decorators like @easy.smart and @easy.cache for ModelAdmin methods, and utilities such as easy.action_response and MixinEasyViews for custom admin views.

Tokens
2.2K
Snippets
7
Records
7
Agent score
18%

What's inside django-admin-easy

  1. Use MixinEasyViews to create custom admin views

    main

    The easy.MixinEasyViews allows you to define custom views within your ModelAdmin that can be accessed via URL.

    1. Add easy.MixinEasyViews to your ModelAdmin inheritance.
    2. Define a method in your ModelAdmin (e.g., easy_view_jump).
    3. Access the view using Django's reverse or the {% url %} template tag with the pattern admin:<app_label>_<model_name>_easy.
    # Python usage
    from django.urls import reverse
    # For a specific object
    url = reverse('admin:myapp_mymodel_easy', args=(obj.pk, 'jump'))
    # For the whole model
    url = reverse('admin:myapp_mymodel_easy', args=('jump',))
    
    # HTML template usage
    # <a href="{% url 'admin:myapp_mymodel_easy' obj.pk 'jump' %}">Jump</a>
  2. Install django-admin-easy

    main

    Install the package using pip. Ensure your environment meets the version requirements for your Django and Python versions.

    For Django > 3 and Python > 3:

    pip install django-admin-easy==0.8.0

    For Django < 2:

    pip install django-admin-easy==0.7.0

    For Django < 1.8 or Python 2.x:

    pip install django-admin-easy==0.4.1
    pip install django-admin-easy==0.8.0
  3. Create computed admin fields using EasyAdminField classes

    main

    Instead of writing verbose methods in your ModelAdmin to display computed data, you can use easy field classes directly as class attributes. This reduces boilerplate for common tasks like displaying images, booleans, or simple model attributes.

    Common field classes include:

    • easy.SimpleAdminField(path_or_lambda, description, order_field): For model fields, methods, or lambdas.
    • easy.BooleanAdminField(lambda_or_value, description, order_field): For boolean displays.
    • easy.ImageAdminField(field_name, extra_attrs): To render images.
    • easy.ForeignKeyAdminField(field_name, display_text): To render a link to the related object's change form.
    • easy.TemplateAdminField(template_name, description, order_field): To render a custom template.
    from django.contrib import admin
    import easy
    
    class YourAdmin(admin.ModelAdmin):
        fields = ('sum_method', 'some_img', 'is_true')
    
        # Using field classes directly
        sum_method = easy.SimpleAdminField(lambda obj: f'<b>{obj.f1 + obj.f2}</b>', 'Sum', 'f1')
        some_img = easy.ImageAdminField('image', 'id')
        is_true = easy.BooleanAdminField(lambda obj: obj.value > 0, 'Positive', 'value')
  4. Create custom admin actions with @easy.action

    main

    Simplify the creation of admin actions using the @easy.action decorator. You can also restrict actions to specific permissions.

    • @easy.action(description): Creates a standard action.
    • @easy.action(description, 'change'): Creates an action only available to users with 'change' permission on the model.
    from django.contrib import admin
    import easy
    
    class YourAdmin(admin.ModelAdmin):
        actions = ('simple_action', 'restricted_action')
    
        @easy.action('My Little Simple Magic Action')
        def simple_action(self, request, queryset):
            return queryset.update(magic=True)
    
        @easy.action('Another Simple Magic Action', 'change')
        def restricted_action(self, request, queryset):
            return queryset.update(magic=True)
  5. Use easy.action_response for admin actions

    main

    When implementing custom actions in a ModelAdmin, use easy.action_response to return a response that redirects the user back to the change list. This utility allows you to display success or error messages and optionally control whether the current URL filters (querystring) are preserved in the redirect.

    Key parameters:

    • request: The current request object.
    • message: The string message to display to the user.
    • level: The Django message level (e.g., messages.SUCCESS, messages.ERROR).
    • keep_querystring: A boolean determining if the current filters should be kept in the redirect URL.
    from django.contrib import admin
    from django.contrib import messages
    import easy
    
    class YourAdmin(admin.ModelAdmin):
        actions = ('simples_action',)
    
        def simples_action(self, request, queryset):
            success = queryset.do_something()
            if success:
                # Redirect and clear filters
                return easy.action_response(request, 'Some success message for user', keep_querystring=False)
            else:
                # Redirect and show error
                return easy.action_response(request, 'Some error for user', messages.ERROR)
    
            # Or just redirect to changelist with current filters preserved
            return easy.action_response()
  6. Decorate admin methods with @easy decorators

    main

    If you prefer defining custom methods on your ModelAdmin class, you can use decorators to quickly set short_description, admin_order_field, and other properties.

    • @easy.smart(short_description, admin_order_field, allow_tags): A comprehensive decorator for setting multiple admin properties.
    • @easy.short(desc, order, tags, bool): A shorthand decorator for common properties.
    • @easy.with_tags(): Automatically wraps the return value in mark_safe() to allow HTML rendering.
    • @easy.filter(filter_name, *args): Applies a Django template filter to the method's output.
    • @easy.cache(seconds): Caches the result of the method for a specified duration.
    from django.contrib import admin
    import easy
    
    class YourAdmin(admin.ModelAdmin):
        fields = ('sum_method', 'some_img', 'is_true')
    
        @easy.smart(short_description='Sum', admin_order_field='field1', allow_tags=True)
        def sum_method(self, obj):
            return f'<b>{obj.field1 + obj.field2}</b>'
    
        @easy.short(desc='image', order='id', tags=True)
        def some_img(self, obj):
            return f'<img src="{obj.image}">'
    
        @easy.short(desc='Positive', order='value', bool=True)
        def is_true(self, obj):
            return obj.value > 0
  7. Clear cached admin fields

    main

    When using the @easy.cache(seconds) decorator, you can manually clear the cache for a specific model instance when its data changes (e.g., in the save() method).

    Use easy.cache_clear(instance) to invalidate the cache for that object.

    import easy
    from django.db import models
    
    class MyModel(models.Model):
        # ... fields
    
        def save(self, *args, **kwargs):
            easy.cache_clear(self)
            super().save(*args, **kwargs)