views:

23

answers:

1

I have a django model and model form that look like this:

-models.py

class Menu_Category(models.Model):
    merchant = models.ForeignKey(Merchant, related_name='menu_categories')
    name = models.CharField(max_length=64)
    test_field = models.CharField(max_length=20)

    def __unicode__(self):
     return self.name

-forms.py

class MenuCategoryForm(ModelForm):
    class Meta:
        model = Menu_Category
        fields = ('name')

The problem i'm experiencing is that when I only select one field from the form to display (fields = ('name')) the form does not display anything nor do i get any errors. It is completely blank. However, when I add a second field fields = ('name','test_field') the form displays both fields just fine. Is there a minimum number of fields a form can display?

Thanks in advance.

+4  A: 

You have been bitten by a common Python gotcha.

In this line:

fields = ('name')

the variable you have created is not a single-element tuple containing the single string "name". Instead, it is a single string, which is iterable, so when Django tries to iterate through it to get the names of the fields, it will think you have set 'n','a','m','e'.

To make a single-element tuple, you always need a trailing comma.

fields = ('name',)

(In fact, as the Python docs show, it is not the parentheses that make the tuple at all, but the comma.)

Daniel Roseman
That did it. Good information to know. That's what I get for switching from python to javascript every 30 seconds (an extra comma at the end of a javascript object produces an error). Thanks.
Justin Lucas