views:

1017

answers:

4

Hi,

I have two models one is Employee and other is Asset, with Many to one relation between Asset and Employee. And Asset is added as StackedInline field to Employee Admin interface, Is there anyway I can make Asset as read only field in the Employee Admin.

My intention was to show all the assets the employee is currently holding in the Admin, so that he will not delete it accidentally.

A: 

I don't think there is a flag in django-admin for that, check out Chapter 18 of the Django book for more details, you'll need to hack the templates by hand

http://www.djangobook.com/en/beta/chapter18/

cheeming
A: 

I think perhaps you can add a custom widget to the fields that's just a basic form except with 'disabled' set on all elements - I cannot tell you how to remove the possibility to add new records though.

Christian P.
+1  A: 

Edit: Actually, I don't think this will work for inline models..

Django will be adding native read-only fields in Django 1.1, which should be released around the middle of March.

Read Only Admin Fields (http://www.djangosnippets.org/snippets/937/)

This snippet will allow you to set fields as read-only in the admin.

Michael Warkentin
+1  A: 

use this code and import it in admin.py as ReadonlyAdmin.This is modified form of readonly admin.

from django import forms
from django.utils.safestring import mark_safe
from datetime import datetime

class ReadOnlyWidget(forms.Widget):
    def __init__(self, original_value, display_value):
        self.original_value = original_value
        self.display_value = display_value
        super(ReadOnlyWidget, self).__init__()

    def render(self, name, value, attrs=None):
        if self.display_value is not None:
            return unicode(self.display_value)
        return unicode(self.original_value)

    def value_from_datadict(self, data, files, name):
        return self.original_value

#to make fields  foreignkey readonly

class ReadOnlyAdminFields(object):
    def get_form(self, request, obj=None):
        form = super(ReadOnlyAdminFields, self).get_form(request, obj)
        if hasattr(self, 'readonly') and obj is not None:
            for field_name in self.readonly:
                if field_name in form.base_fields:
                    if hasattr(obj, 'get_%s_display' % field_name):
                        display_value = getattr(obj, 'get_%s_display' % field_name)()
                    else:
                        display_value = None
                    if getattr(obj, field_name).__class__ in [unicode , long, int, float, datetime, list]:
                        form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name), display_value)
                    else:
                        form.base_fields[field_name].widget = ReadOnlyWidget(getattr(obj, field_name).id, display_value)
            form.base_fields[field_name].required = False
        return form
ha22109