Writing your own django widget

I wrote a django app which uses tratto to fetch router configurations.  These configurations are stored in a TextField defined in a model named "Output."  I wanted to display this readonly field in a  preformatted block.  At first I used fieldsets and defined a specific class to the fieldset to solve the problem using css.  I didn't like what I saw so I decided to write a simple widget which would simply render my field's value wrapped with a "pre" tag.


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

class PreformattedTextWidget(forms.Widget):
   def render(self, name, value, attrs=None):
   return mark_safe("<br/><pre>%s </pre>" %(value))


from django.contrib import admin
from django.db import models
from tratto.models import *
from tratto.widgets import *

class OutputAdmin(admin.ModelAdmin):
   formfield_overrides = {
      models.TextField: {'widget': PreformattedTextWidget},

This essentially overrides the default widget for TextField in my Output model and uses the PreformattedTextWidget which simply prints the value wrapped in pre tags

Tagged as custom widget , django widget
Written by Andrew Konkol on June 18th, 2012


Log in with Twitter, Google, Facebook, LinkedIn to leave a comment.