开发者

Cleaning data which is of type URLField

开发者 https://www.devze.com 2023-01-15 14:21 出处:网络
I have a simple URLField in my model link 开发者_如何转开发= models.URLField(verify_exists = False, max_length = 225)

I have a simple URLField in my model

link 开发者_如何转开发= models.URLField(verify_exists = False, max_length = 225)

I would like to strip the leading and trailing spaces from the field. I don't think I can do this in "clean_fieldname" or in the "clean" method.

Do I need to sub-class the "URLField" and remove the spaces in to_python method? Is there a better way to do this without any sub-classing?

Edited

This is my form

class StoryForm(forms.ModelForm):

    title = forms.CharField(max_length=225, error_messages={'required' : 'Enter a title for the story'})
    link = forms.URLField(max_length=225, error_messages={'required' : 'Enter a link to the story', 'invalid' : 'Enter a valid link like www.ted.com'})

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

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

and my model

class Story(models.Model):
    title = models.CharField(max_length = 225)
    link = models.URLField(verify_exists = False, max_length = 225)


I did a quick experiment and found out that you can indeed use a clean_ method to remove leading/trailing spaces. Something like this:

# models.py
class UrlModel(models.Model):
    link = models.URLField(verify_exists = False, max_length = 225)

    def __unicode__(self):
        return self.link

# forms.py 
class UrlForm(ModelForm):
    class Meta:
        model = UrlModel

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

# shell
In [1]: from test_app.forms import UrlForm

In [2]: f = UrlForm(data = dict(link = '  http://google.com  '))

In [3]: f.is_valid()
Out[3]: True

In [4]: f.save()
Out[4]: <UrlModel: http://google.com>

Update

I get an error saying "Enter a valid link like www.ted.com". I edited my question and included the model and form in question.

I verified that your form class does give the error.

After making a small change I was able to make it work. All I did was remove the custom title and link fields. We are working with a model form here and the underlying model already has these fields. I believe the redefinition led to a validation error being raised before the custom clean method was invoked.

class StoryForm(forms.ModelForm):
    class Meta:
        model = Story
        fields = ('title', 'link')

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

Here is some sample output from the shell:

In [1]: from test_app.forms import StoryForm

In [2]: data = dict(title="Google story", link  = "   http://google.com ")

In [3]: f = StoryForm(data)

In [4]: f.is_valid()
Out[4]: True

In [5]: f.save()
Out[5]: <Story: Google story http://google.com>
0

精彩评论

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