Stephan Jaekel avatar Stephan Jaekel committed 34f13a6

initial import

Comments (0)

Files changed (6)

+Stephan Jaekel <http://www.sjaekel.com/>
+Copyright (c) 2009, Stephan Jaekel <http://www.sjaekel.com/>
+All rights reserved.
+ 
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+ 
+    * Redistributions of source code must retain the above copyright notice,
+      this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above copyright notice,
+      this list of conditions and the following disclaimer in the documentation
+      and/or other materials provided with the distribution.
+    * Neither the name django-readonlywidget nor the names of its contributors
+      may be used to endorse or promote products derived from this software without
+      specific prior written permission.
+    * If you meet the author(s) some day, and you think this stuff is worth it,
+      you can buy the author(s) a beer in return.
+ 
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+=====================
+django-readonlywidget
+=====================
+
+ReadOnlyWidget is a widget to display many kinds of django's modelfields read-only.
+
+**Currently supported modelfields:**
+ - TextField
+ - CharField
+ - IntegerField
+ - BooleanField
+ - FileField
+ - ImageField
+ - ForeignKey
+ - ManyToManyField
+ - DateTimeField
+ - DateField
+
+
+Extend the widget
+=================
+
+It's easy to extend the widget. Just subclass it and add your *get_modelfield_value* method.
+Look at the existing methods to understand, how it works.
+
+Usage
+=====
+
+To use the widget, import it from *django_readonlywidget.widgets* and use *ReadOnlyWidget* as your *forms.Field* widget.
+The usage in django's admin application is described in the example below.
+
+Quick Example:
+==============
+
+::
+
+    from django_readonlywidget.widgets import ReadOnlyWidget
+
+    class TestAdmin(admin.ModelAdmin):
+        def formfield_for_dbfield(self, db_field, \**kwargs):
+            field = super(TestAdmin, self).formfield_for_dbfield(db_field, \**kwargs)
+            if field:
+                field.widget = ReadOnlyWidget(db_field=db_field)
+            return field
+
+
+Have fun!
Add a comment to this file

django_readonlywidget/__init__.py

Empty file added.

django_readonlywidget/widgets.py

+from django import forms
+from django.utils.safestring import mark_safe
+from django.utils.encoding import force_unicode
+from django.utils.html import escape, conditional_escape
+from django.contrib.admin.templatetags.admin_list import _boolean_icon
+
+class ReadOnlyWidget(forms.HiddenInput):
+    def __init__(self, db_field, *args, **kwargs):
+        self.db_field = db_field
+        super(ReadOnlyWidget, self).__init__()
+
+    def render(self, *args, **kwargs):
+        field_name, value = args
+        field_type = self.db_field.__class__.__name__
+        field_value = super(ReadOnlyWidget, self).render(*args, **kwargs)
+        output = value
+
+        if hasattr(self, 'get_%s_value' % field_type.lower()):
+            try:
+                func = getattr(self, 'get_%s_value' % field_type.lower())
+                output = func(field_name, value)
+            except Exception,e:
+                output = e
+        else:
+            raise Exception('%s is not supported by ReadOnlyWidget.' % field_type)
+
+        return self.render_output(field_name, field_value, output)
+
+    def render_output(self, field_name, field_value, output):
+        return mark_safe('%s %s' % (output, field_value))
+
+    def get_textfield_value(self, field_name, value):
+        return '<p style="clear:both;">%s</p>' % value
+
+    def get_charfield_value(self, field_name, value):
+        if self.db_field.choices:
+            for choice in self.field.choices:
+                if value == choice[0]:
+                    return conditional_escape(force_unicode(choice[1]))
+        else:
+            return escape(value)
+
+    def get_integerfield_value(self, field_name, value):
+        return '%d' % value
+
+    def get_booleanfield_value(self, field_name, value):
+        return _boolean_icon(value)
+
+    def get_filefield_value(self, field_name, value):
+        if value:
+            return '%s <a target="_blank" href="%s">%s</a>' % ('Currently:', value.url, value.name)
+        else:
+            return ''
+
+    def get_imagefield_value(self, field_name, value):
+        return self.get_filefield_value(field_name, value)
+
+    def get_foreignkey_value(self, field_name, value):
+        try:
+            obj = self.db_field.rel.to.objects.get(**{self.db_field.rel.get_related_field().name: value})
+            return '<strong>%s</strong>' % unicode(obj)
+        except:
+            return ''
+
+    def get_manytomanyfield_value(self, field_name, value):
+        output = ['<ul class="m2m_list_%s">' % field_name,]
+        for id in value:
+            output.append('<li>%s</li>' % unicode(self.db_field.rel.to.objects.get(pk=id)))
+        output.append('</ul>')
+        print self.help
+        return ''.join(output)
+
+    def get_datetimefield_value(self, field_name, value):
+        if value:
+            return value.strftime('%x %X')
+        else:
+            return ''
+
+    def get_datefield_value(self, field_name, value):
+        if value:
+            return value.strftime('%x')
+        else:
+            return ''
+from setuptools import setup, find_packages
+ 
+setup(
+    name='django-readonlywidget',
+    version='0.1',
+    description='A ReadOnly Widget for Django',
+    author='Stephan Jaekel',
+    author_email='steph@rdev.info',
+    url='http://bitbucket.org/stephrdev/django-readonlywidget/overview/',
+    packages=find_packages(),
+    classifiers=[
+        'Development Status :: 3 - Alpha',
+        'Environment :: Web Environment',
+        'Intended Audience :: Developers',
+        'License :: OSI Approved :: BSD License',
+        'Operating System :: OS Independent',
+        'Programming Language :: Python',
+        'Framework :: Django',
+    ],
+    zip_safe=False,
+)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.