views:

23

answers:

1

Is there a way to add a custom error message to a model field without declaring it in the form as a form field? Is this possible?

I don't want to declare the field again, for example

class MyModel(models.Model):
    test = models.URLField(max_length = 200)

class MyForm(forms.ModelForm):
    test = forms.URLField(max_length = 200, error_messages={'required' : 'Custom error message'})
    class Meta:
        model = models.test

Is there a way to provide a custom error message without defining it again in the form?

Edited Model

class MyModel(models.Model):
    link = models.URLField(verify_exists = False, max_length = 225, error_messages={'required' : 'Link cannot be left blank.'})

Edit

I should clarify that I also have a model form for my model. This is the actual code

class Story(models.Model):
    title = models.CharField(max_length = 225, error_messages={'required' : 'cannot be left blank'})
    link = models.URLField(verify_exists = False, max_length = 225, error_messages={'required' : ugettext_lazy(u"Link cannot be left blank.") })

form

class StoryForm(forms.ModelForm):

    class Meta:
        model = models.Story
        fields = ('title', 'link')

    def clean_link(self):
        link = self.cleaned_data['link']
        return link.strip()

    def clean_title(self):
        title = self.cleaned_data['title']
        return title.strip()

I don't want to declare the fields in my form because then I run into this issue discussed here

http://stackoverflow.com/questions/3653423/cleaning-data-which-is-of-type-urlfield

A: 

By setting error_messages in model fields for example.

rebus
I tried that but I cannot get it work. If I leave the field blank it always says "Thie field is required". This is what I had link = models.URLField(verify_exists = False, max_length = 225, error_messages={'required' : 'Link cannot be left blank.'})
iHeartDucks
There was an open ticket in django (http://code.djangoproject.com/ticket/13693). I fixed it using the patch.
iHeartDucks
Yup, was just looking at it... It doesn't seem to work. I would rather use workaround then patch Django if i were you.
rebus