Note that there are some explanatory texts on larger screens.

plurals
  1. PODjango - custom widget - why does Django think I don't have 'attrs'?
    text
    copied!<p><em>EDIT: Using Django 1.3</em></p> <p>I've built a Custom Widget to educate myself but I can't get past a problem where when the page is fetched Django says that:</p> <pre><code>'FooTestWidget' object has no attribute 'attrs' </code></pre> <p>I don't want to use the 'attrs' argument and I've set it to default to None (also tried an empty dictionary, eg {}) so I'm confused about why Django is complaining.</p> <p><strong>widgets.py</strong></p> <pre><code>class FooTestWidget(Widget): """ A very silly widget to test I can do anything """ def __init__(self, attrs=None): pass def render(self, name, value, attrs=None): tpl = Template(u"""&lt;h1&gt;This is here instead of a CharField&lt;/h1&gt;""") return mark_safe(tpl.substitute(colour=value)) </code></pre> <p><strong>admin.py</strong></p> <pre><code>class UserAdminForm(ModelForm): class Meta: model = User widgets = { 'name_family': FooTestWidget, } class UserAdmin(admin.ModelAdmin): form = UserAdminForm </code></pre> <p><strong>model.py</strong></p> <pre><code>class User(models.Model): id = models.AutoField(primary_key=True, db_column='USE_ID') name_given = models.CharField(max_length=200, db_column='USE_NAME_GIVEN') name_family = models.CharField(max_length=200, db_column='USE_NAME_FAMILY') </code></pre> <hr> <p><strong>WORKING VERSION AFTER HELP FROM DANIEL</strong></p> <p>Here's a working version of widgets.py after taking on board what Daniel explained in his answer and then me making one or two other small changes (which weren't assocated with the problem described here but which stopped it working as it should). This version now works as I expected it to:</p> <pre><code>from datetime import date import re from django.forms.widgets import Widget, Select from django.utils.safestring import mark_safe from django.forms import widgets from django.template.base import Template __all__ = ('FooTestWidget',) RE_DATE = re.compile(r'(\d{4})-(\d\d?)-(\d\d?)$') class FooTestWidget(Widget): """ A very silly widget to test I can do anything """ #def __init__(self, attrs={}): # pass def render(self, name, value, attrs=None): sout = u"""&lt;h1&gt;This is here instead of a CharField&lt;/h1&gt;""" return mark_safe(sout) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload