Showing posts with label admin. Show all posts
Showing posts with label admin. Show all posts

Mar 21, 2012

Django Admin Actions — действия с промежуточной страницей

http://habrahabr.ru/post/140409/ Хочу поделиться как можно сделать экшен который после выбора элементов будет отправлять пользователя на промежуточную страницу чтобы с этими элементами можно было сделать что то особенное. Например у вас есть интернет магазин, таблица товаров. Вы хотите перенести часть товаров из одного раздела (книги) в другой (книги технические). Выбираем нужные книги, выбираем действие «Перенести в другой раздел», жмем применить, переходим на промежуточную страницу, выбираем нужный раздел и жмем сохранить. Описываем форму:
class ChangeCategoryForm(forms.Form):
    _selected_action = forms.CharField(widget=forms.MultipleHiddenInput)
    category = forms.ModelChoiceField(queryset=Category.objects.all(), label=u'Основная категория')
Загадочное поле _select_action, да? Тут будут ID выбранных элементов. Django заберет их потом из POST запроса и сделает из них Queryset для которого мы будем делать наши действия (см. код ниже). Наш экшен это как и всегда метод. Назовем его move_to_category.
def move_to_category(modeladmin, request, queryset):
       form = None

       if 'apply' in request.POST:
           form = ChangeCategoryForm(request.POST)

           if form.is_valid():
               category = form.cleaned_data['category']

               count = 0
               for item in queryset:
                   item.category = category
                   item.save()
                   count += 1

               modeladmin.message_user(request, "Категория %s применена к %d товарам." % (category, count))
               return HttpResponseRedirect(request.get_full_path())

       if not form:
           form = ChangeCategoryForm(initial={'_selected_action': request.POST.getlist(admin.ACTION_CHECKBOX_NAME)})

       return render(request, 'catalog/move_to_category.html', {'items': queryset,'form': form, 'title':u'Изменение категории'})

move_to_category.short_description = u"Изменить категорию"
Объявляем экшен в класс ProductAdmin:
actions = [move_to_category,]
И создаем шаблон для показа всего этого
{% extends "admin/base_site.html" %}

{% block content %}
<form action="" method="post">{% csrf_token %}
    {{ form }}
    <p>Новая категория будет назначена для следующих позиций:</p>
    <ul>{{ items|unordered_list }}</ul>
    <input type="hidden" name="action" value="move_to_category" />
    <input type="submit" name="apply" value="Сохранить" />
</form>
{% endblock %}

Jan 20, 2012

How to override the verbose name of a superclass model field in django

class SuperFoo(models.Model):
    name = models.CharField('name of SuperFoo instance', max_length=50)
    ...

class Foo(SuperFoo):
    ... # do something that changes verbose_name of name field of SuperFoo
    Foo._meta.get_field('name').verbose_name = 'Whatever'

Dec 29, 2011

Monkey patch удаляющий "view on site" кнопку

from django.contrib.auth.models import User
del User.get_absolute_url

Dec 16, 2011

Readonly Tabluar Inline

# admin.py

class ReadonlyTabularInline(admin.TabularInline):
    can_delete = False
    extra = 0
    editable_fields = []
    
    def get_readonly_fields(self, request, obj=None):
        fields = []
        for field in self.model._meta.get_all_field_names():
            if (not field == 'id'):
                if (field not in self.editable_fields):
                    fields.append(field)
        return fields
    
    def has_add_permission(self, request):
        return False
    

# Usage Example (admin.py)

class FixturesInline(ReadonlyTabularInline):
    model = models.Fixture
    verbose_name_plural = _('List of unpublished Fixtures')
    editable_fields = ['public']



# My models.py (a part of)

class Competition(models.Model):
    name = models.CharField(max_length=200)
    location = models.ForeignKey(Location)

class Fixture(models.Model):
    competition = models.ForeignKey(Competition)
    conference = models.BooleanField()
    home_team = models.ForeignKey(Team, related_name='hometeam')
    guest_team = models.ForeignKey(Team, related_name='guestteam')
    datetime = models.DateTimeField()
    public = models.BooleanField()
    channels = models.ManyToManyField(ChanSatMembership)
    additional_infos = models.TextField(blank=True, null=True)

Nov 7, 2011

Django soft delete

django-softdelete Soft delete for Django ORM, with support for undelete

Oct 11, 2011

500/404 templates if you only use the admin

If you have a project that only exposes the admin you should just use the 500/404 templates from the admin.

urls.py:
from django.utils.functional import curry
from django.views.defaults import server_error, page_not_found

handler500 = curry(server_error, template_name='admin/500.html')
handler404 = curry(page_not_found, template_name='admin/404.html')
If you have other drop-in apps that need authentication (like rosetta or sentry) bare in mind that the admin doesn’t have a reusable login view so you must hook one. You should just reuse django admin’s login template.
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),

Aug 30, 2011

Django Admin Snippets

readonly_field

As of Django 1.2, a readonly_field has been available to models in the admin. This is very helpful for making data visible in the admin while preventing it from being edited.

readonly_fields=[’created’,’modified’,’preformed_by’,’ipaddress’,’featured’]

get_readonly_fields()

Using the get_readonly_fields() method of the ModelAdmin, one can change readonly fields dynamically. The method gives access both to the request and to the Admin Model instance.

def get_readonly_fields(self, request, obj = None):
    if obj: 
        if not (request.user.is_staff or request.user.is_superuser):
            return [‘featured’,] + self.readonly_fields
        return self.readonly_fields
    else:
        return self.readonly_fields

Disable admin actions

By default, every Django Admin model has a delete_selected admin action available which allows admins to delete multiple objects in the change_list admin view. If you wish to remove this default option and disable all the admin actions for a given Django Model in the Admin, something like this may be appropriate. This will remove the “Actions” dropdown completely from the model’s change list.

admin_actions = None

Override get_actions

An alternative to disabling all the admin actions for a Model would be to override the get_actions() method on the ModelAdmin. This will allow you to customize the “Actions” list based on the request or other factors.
http://stackoverflow.com/questions/1565812/the-default-delete-selected-admin-action-in-django

def get_actions(self, request):
    actions = super(PostAdmin, self).get_actions(request)
    try:
        del actions[‘delete_selected’]
    except KeyError:
        pass 
    return actions

Customize permissions

The has_delete_permission() ModelAdmin method allows you to customize how permissions are assigned for a given model in the admin. Instead of using Django’s default permission system, you can change the permissions programmatically. Note that this function does not change how permissions work on admin actions such as the delete_selected action discussed above.

def has_delete_permission(self, request, obj=None):
    return_value = False
    user = request.user
    if user.is_authenticated() and user.is_staff:
        return_value = True
    return return_value

The has_add_permission() allows the same type of customization of permissions for adding objects.

def has_add_permission(self, request):
    return_value = False
    user = request.user
    if user.is_authenticated() and user.is_superuser:
        return_value = True
    return return_value

Customize save_model

The save_model() method allows you to customize actions that take place on the model only when it’s saved in the admin. In this example, we override the save_model() so that we may save to the model of the current admin user and her IP address.

def save_model(self, request, obj, form, change):
    obj.preformed_by = request.user
    obj.ip_address = utils.get_client_ip(request)
    obj.save()

Change multiple-select widget to filter_horizontal for ManyToMany fields

When dealing with ManyToMany fields, the default admin widget is a multiple-select box which allows a user to control-select a list of multiple items. This select box is kind of awkward; a better option may be to use the Filter Horizontal widget which provides a more advanced box.

filter_horizontal = ('category',)

For performance reasons use raw_id_fields instead filter_horizontal

For performance reasons, it may not be a good idea to use the Django default widget or the filter_horizontal widget for ManyToMany relations where a lot of related results. For example, a filter_horizontal Admin widget may take a long time to load if used to display a related tags field if there are thousands of possible related Tags. In that case, the raw_id_fields Admin option may be more appropriate, as it will only display the ID field and unicode representation of the related object. This option also provides a link to a popup dialog that allows an admin to populate the id field by browsing for an object interactively.

raw_id_fields = ("tags",)

Dynamically define fieldsets

The Django Admin offers some flexibility in how the fields on the detail pages are displayed. Fieldsets are used to group Admin fields into sections and even together on the same line. This can be done dynamically by overriding the __init__() on the ModelAdmin.

fieldsets = []
  
def __init__(self, model, admin_site):    
    # Define some field groupings
    post_fields = ['title', 'type', 'featured']
    meta_fields = ['created', 'modified',]
    client_fields = ['preformed_by', 'ipaddress']
    message_fields = ['message',]       

    # make a big list of all the fields that we are customizing 
    ex_fields = post_fields + meta_fields + client_fields + message_fields
    all_fields = fields_for_model(model)
      
    base_fields = [tuple(post_fields), tuple(meta_fields), tuple(message_fields)]
 
    # all the rest of the fields that we don’t specifically customize
    rest_fields = list(set(all_fields) - set(ex_fields))
 
    # Group fields into Sections
    self.fieldsets.append(('Post Info', { 'fields': tuple(base_fields), }))
    self.fieldsets.append(('Client Info', { 'fields': tuple(client_fields), }))
        
    # Display the rest of the non-customized fields at the bottom
    if rest_fields:
        self.fieldsets.append(('Other', { 'fields': tuple(rest_fields), }))

    # set the fieldset - needs to be a tuple 
    self.fieldsets = tuple(self.fieldsets)

    super(PostAdmin, self).__init__(model, admin_site)

admin.site.register(models.Post, PostAdmin)

Customize User model

Sometimes it’s nice to be able to customize the admin page for the Django user. This can be done by un-registering the default ModelAdmin class and re-registering your customized version. This code should be placed in any one of your Django App’s admins.py files. In this example, we add a custom Inline class to the User Admin, as well as modify the list_display and list_filter fields for the User Admin.

from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

class PostInline(admin.TabularInline):
    model = models.Post
    extra = 0
    readonly_fields = ['created', 'modified', 'preformed_by', 'ip_address']
    exclude = ['tags','category',]

class CustomUserAdmin(UserAdmin):
    list_display = UserAdmin.list_display + ('date_joined','last_login')
    list_filter = UserAdmin.list_filter + ('is_active',)
    inlines = [PostInline,]

admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)

Customize User form

The form that an Admin model uses can be customized as well. For example, you can place extra validation on the Admin form to ensure that the admin users enter data correctly.

class PostAdminForm(forms.ModelForm):
    class Meta:
        model =  models.Post

    def clean(self):
        cleaned_data = self.cleaned_data
        message = cleaned_data.get("message", False)

        if len(message) < 20:
            raise forms.ValidationError("Message must be 20+ chars long.")

        return cleaned_data

Set the form by adding it to the PostAdmin ModelAdmin.

class PostAdmin(admin.ModelAdmin):
   ...
   ...   
   form = PostAdminForm 
   ...

Override “Django Administration”

One convenient admin customization is to override the default “Django Administration” title that appears at the top of the admin interface. This can be done via an admin template override.

Let’s say our settings.py has our TEMPLATE_DIRS set as follows, where PROJECT_PATH is the UNIX filesystem path to the Django Project.

import os
PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
TEMPLATE_DIRS = (
   os.path.join(PROJECT_PATH, 'templates'),
)

We could create a file called base_site.html located in PROJECT_PATH/templates/admin/ which contains the following Django template code. This overrides the default title for the Django admin.

{# Located in PROJECT_PATH/templates/admin/base_site.html #}

{% extends "admin/base.html" %}
{% load i18n %}

{% block title %}{{ title }} | {% trans 'ChicagoDjango Demo Project Admin' %}{% endblock %}

{% block branding %}
<h1 id="site-name">{% trans 'ChicagoDjango Demo Project Administration' %}</h1>{% endblock %}

{% block nav-global %}{% endblock %}

Add extra “sections” to the Django admin on a given Object Change page

Sometimes you may want to add extra “sections” to the Django admin on a given Object Change page (change_form.html). This can be done with an admin template override and template inheritance. In order to override the default admin template for the Object Change view, you need to place a file named change_form.html in the following directory within your Django module directory, where your_module_name and your_model_name refers to the lower-case names of your Django module and Django model respectively: templates/admin/<your_module_name>/<your_model_name>/.

Notice in the code below that this custom template overrides admin/change_form.html. Also, this custom template defines a block called {% block after_field_sets %} which adds a template block at the bottom of the page. You can reference the object being edited as a context variable called “original”.
</your_model_name>/<your_module_name>

{# Located in MODULE_PATH/templates/admin/a/post/change_form.html #}

{% extends "admin/change_form.html" %}

{% block extrahead %}{{ block.super }}
<style>
  .item { padding: 10px; border-bottom:1px solid #EEEEEE; height: 25px }
  .heading { font-weight: bold; font-size: 14px; color: #666666;  }
</style>
{% endblock %}

{% block after_field_sets %}{{ block.super }}

<div class="module aligned">
    <div class="item">Post: {{ original.title }}</div>
</div>

<div class="module aligned">
    <div class="item heading">Post Categories</div>
    {% for category in original.category.all %}  
    <div class="item">
        <span class="item_name">{{ category.name }}</span>
        <span class="item_edit"><a href="{% url admin:a_postcategory_change category.id %}" target="_blank">Edit</a></span>
    </div>
    {% empty %}
    <div class="item">No Categories</div>{% endfor %}
</div>
{% endblock %}

When it comes to customizing the Django admin, this is just the tip of the iceberg. Please feel free to share any admin customizations that you find interesting via a comment. Also, feel free to fork the Github repository and suggest updates or additional techniques.

Original http://www.chicagodjango.com/blog/django-admin-snippets/

Jul 18, 2011

Rename django admin app name and breadcrumbs

from django.db.models.base import ModelBase
from django.core.urlresolvers import resolve

class AppLabelRenamer(object):
    ''' Rename app label and app breadcrumbs in admin. '''
    def __init__(self, native_app_label, app_label):
        self.native_app_label = native_app_label
        self.app_label = app_label
        self.module = '.'.join([native_app_label, 'models'])

    class string_with_realoaded_title(str):
        ''' tnx to Ionel Maries Cristian for http://ionelmc.wordpress.com/2011/06/24/custom-app-names-in-the-django-admin/'''
        def __new__(cls, value, title):
            instance = str.__new__(cls, value)
            instance._title = title
            return instance

        def title(self):
            return self._title

        __copy__ = lambda self: self
        __deepcopy__ = lambda self, memodict: self

    def rename_app_label(self, f):
        app_label = self.app_label

        def rename_breadcrumbs(f):
            def wrap(self, *args, **kwargs):
                extra_context = kwargs.get('extra_context', {})
                extra_context['app_label'] = app_label
                kwargs['extra_context'] = extra_context
                return f(self, *args, **kwargs)
            return wrap

        def wrap(model_or_iterable, admin_class=None, **option):
            if isinstance(model_or_iterable, ModelBase):
                model_or_iterable = [model_or_iterable]
            for model in model_or_iterable:
                if model.__module__ != self.module:
                    continue
                if admin_class is None:
                    admin_class = type(model.__name__+'Admin', (admin.ModelAdmin,), {})
                admin_class.add_view = rename_breadcrumbs(admin_class.add_view)
                admin_class.change_view = rename_breadcrumbs(admin_class.change_view)
                admin_class.changelist_view = rename_breadcrumbs(admin_class.changelist_view)
                model._meta.app_label = self.string_with_realoaded_title(self.native_app_label, self.app_label)
            return f(model, admin_class, **option)
        return wrap

    def rename_app_index(self, f):
        def wrap(request, app_label, extra_context=None):
            requested_app_label = resolve(request.path).kwargs.get('app_label', '')
            if requested_app_label and requested_app_label == self.native_app_label:
                app_label = self.string_with_realoaded_title(self.native_app_label, self.app_label)
            else:
                app_label = requested_app_label
            return f(request, app_label, extra_context=None)
        return wrap

    def main(self):
        admin.site.register = self.rename_app_label(admin.site.register)
        admin.site.app_index = self.rename_app_index(admin.site.app_index)

# Example
AppLabelRenamer(native_app_label=u'exampleapp', app_label=u'your custom label').main()

Оригинал: http://djangosnippets.org/snippets/2488/

См. также: Изменение названия модуля в django admin

Jun 25, 2011

Изменение названия модуля в django admin

class Stuff(models.Model):
    class Meta:
        verbose_name = u'The stuff'
        verbose_name_plural = u'The bunch of stuff'
django admin использует app_label.title() поэтому мы можем использовать небольшой хак: подкласс str с переопределенным методом title:
class string_with_title(str):
    def __new__(cls, value, title):
        instance = str.__new__(cls, value)
        instance._title = title
        return instance

    def title(self):
        return self._title
и в итоге получаем:
class Stuff(models.Model):
    class Meta:
        app_label = string_with_title("stuffapp", "The stuff box")
        # 'stuffapp' is the name of the django app
        verbose_name = 'The stuff'
        verbose_name_plural = 'The bunch of stuff'

См. также: Rename django admin app name and breadcrumbs

Jun 17, 2011

Как в администрировании Django сделать action без обязательного выбора чекбокса

Есть action создания контактов для emencia-django-newsletter из ордеров

def make_mailing_list_all(self, request, queryset):
        from emencia.django.newsletter.models import Contact
        from emencia.django.newsletter.models import MailingList

        subscribers = []
        for order in OrderRecurring.objects.filter(status='active'):
            contact, created = Contact.objects.get_or_create(email=order.customer_email,
                                                           defaults={'first_name': order.customer_first_name,
                                                                     'last_name': order.customer_last_name,
                                                                     'content_object': order})
            subscribers.append(contact)
        new_mailing = MailingList(name='All Order recurrings mailing list',
                                  description='New mailing list created from all order recurrings')
        new_mailing.save()
        new_mailing.subscribers.add(*subscribers)
        new_mailing.save()
        self.message_user(request, '%s succesfully created.' % new_mailing)
    make_mailing_list_all.short_description = _('Create a mailing list for all active recurring orders')

    actions = ['make_mailing_list_all',]


Стандартно, если в списке не выбран ни один чекбокс, action не срабатывает. Нужно переписать метод admin.ModelAdmin.response_action:


    def response_action(self, request, queryset):
        from django.contrib.admin import helpers
        try:
            action_index = int(request.POST.get('index', 0))
        except ValueError:
            action_index = 0

        data = request.POST.copy()
        data.pop(helpers.ACTION_CHECKBOX_NAME, None)
        data.pop("index", None)

        try:
            data.update({'action': data.getlist('action')[action_index]})
        except IndexError:
            pass

        action_form = self.action_form(data, auto_id=None)
        action_form.fields['action'].choices = self.get_action_choices(request)

        if action_form.is_valid():
            action = action_form.cleaned_data['action']
            func, name, description = self.get_actions(request)[action]

            selected = request.POST.getlist(helpers.ACTION_CHECKBOX_NAME)
            ### CHANGED ###
            if not selected:
                if action == u'make_mailing_list_all':
                    pass
                else:
                    return None
            else:
                queryset = queryset.filter(pk__in=selected)

            response = func(self, request, queryset)
            ### END CHANGED ###

            if isinstance(response, HttpResponse):
                return response
            else:
                return HttpResponseRedirect(".")