0

I have a drop down which is populated from an underlying table, however when rendering there is no value selected on the drop down or rather "-------" is shown. Needless to say "------" does not corresponds to any table rows.

Here is the code:

class CompanyCategory(db.Model):
    categoryname = db.StringProperty(required=False)

    def __unicode__(self):
            return u'%s' % (self.categoryname)

class SelectCategoryForm(djangoforms.ModelForm):
    class Meta:
            model = SelectCat

The code is rendered with this code in the html

{ form.companycategory }}

Here is the error:

Traceback (most recent call last):
  File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/_webapp25.py", line 703, in __call__
    handler.post(*groups)
  File "/base/data/home/apps/s~biomapit/1.359892355004556500/showcompanies.py", line 163, in post
    mycategoryid = [form_requirements.clean_data['companycategory'].key().id()]
AttributeError: 'NoneType' object has no attribute 'key'

How do I get the default changed or remove the "-----" when the drop-down is rendered. There is no difference if I change the categoryname = db.StringProperty(required=False) line to categoryname = db.StringProperty(required=True).

As an extra attempt following one response, I have tried:

class SelectCategoryForm(djangoforms.ModelForm):    
    class Meta:
            model = SelectCat
    def __init__(self, *args, **kwargs):
            super(SelectCategoryForm, self).__init__(*args, **kwargs)
            modelchoicefields = [field for field_name, field in self.fields.iteritems() if isinstance(field, forms.ModelChoiceField)]
            for field in modelchoicefields:
                field.empty_label = None

to no avail - I still get the "-----".

Androidian
  • 553
  • 2
  • 7
  • 16

1 Answers1

1

I think you are looking for empty_label

# A custom empty label
field1 = forms.ModelChoiceField(queryset=..., empty_label="(Nothing)")

# No empty label
field2 = forms.ModelChoiceField(queryset=..., empty_label=None)

This will help you more.

Community
  • 1
  • 1
Ahsan
  • 11,516
  • 12
  • 52
  • 79
  • Thanks, I followed some of the comments you made about the model field, but I'm still having some trouble. I've followed the following code recommendation from http://stackoverflow.com/questions/4692676/modelchoicefield-removing-the-blank-choice, however using the following code, I'm still finding that I cannot get rid of the "------". – Androidian Jun 26 '12 at 15:52