Better error message for missing trailing comma in ModelForm fields attribute

222 views
Skip to first unread message

Sachin Gupta

unread,
Mar 22, 2012, 9:44:56 AM3/22/12
to django-d...@googlegroups.com
I have the following ModelForm, that has a valid field body. 

class PostForm(ModelForm):

    class Meta:
        model = Post
        fields = ('body')
      
However when I validate the models, the following error comes up

django.core.exceptions.FieldError: Unknown field(s) (y, b, d, o) specified for Post

This is because the Django expects a 'list' in the fields attribute. The error can be solved by adding a trailing comma

fields = ('body',)

This problem is quite common, as people tend to forget the trailing comma. I have written a small hack for this problem, that throws the following error message if the trailing comma is missing

django.core.exceptions.FieldError: Missing trailing comma in fields attribute

This error message is more intuitive than the one that is thrown currently

Editions:

In django/forms/models.py

class ModelFormOptions(object):
    def __init__(self, options=None):
        self.model = getattr(options, 'model', None)
        self.fields = getattr(options, 'fields', None)
        self.exclude = getattr(options, 'exclude', None)
        self.widgets = getattr(options, 'widgets', None)

        if isinstance(self.fields,str):
            message = 'Missing trailing comma in fields attribute'
            raise FieldError(message)

        if isinstance(self.exclude,str):
            message = 'Missing trailing comma in exclude attribute'
            raise FieldError(message)

I am raising a FieldError but a TypeError could also be raised. 

Regards
Sachin Gupta






Andre Terra

unread,
Mar 22, 2012, 11:43:26 AM3/22/12
to django-d...@googlegroups.com

I have a feeling that this is too much to ask from the framework, after all it shouldn't have to teach python, so I'm -0 on the proposed change.

Additionally, if users specify fields = 'body' with no parenthesis they would get the same error message and probably think "but I don't need a comma, it's just one field" or even write fields = 'body', which is just horrible..

Cheers,
AT

--
You received this message because you are subscribed to the Google Groups "Django developers" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-developers/-/biHIzxoCrD0J.
To post to this group, send email to django-d...@googlegroups.com.
To unsubscribe from this group, send email to django-develop...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.
Reply all
Reply to author
Forward
0 new messages