开发者

Adding custom error messages to a ModelForm field

开发者 https://www.devze.com 2023-01-15 00:01 出处:网络
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?

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

Cleaning data which is of type URLField


By setting error_messages in model fields for example.

0

精彩评论

暂无评论...
验证码 换一张
取 消