开发者

Fixing and cleaning form input in Django

开发者 https://www.devze.com 2023-03-25 04:10 出处:网络
Presumably the clean_ methods in Django are designed to allow inline cle开发者_如何转开发aning of input form data as well as accepting/rejecting submissions.

Presumably the clean_ methods in Django are designed to allow inline cle开发者_如何转开发aning of input form data as well as accepting/rejecting submissions.

Given a model where

"FooBar"

is valid input. Is there a standard way of fixing things like

"FOOBAR"
"foo-bar"
"FooBar "

in a somewhat fuzzy and generalizable manner before validation?


Okay it is unclear what you actually want to do about changing, but something like this should work:

from re import sub
...
#in your form:
def clean_myfield(self):
    data = self.cleaned_data['myfield']
    #Strip special chars
    data = sub("[\s_\-]","",a)
    if b.lower() != "foobar":
        raise forms.ValidationError("You have not specified foobar, you wicked boy!")
    #Do whatever conversion to camelcase you want on data (this seemed very app specific to me)
    return data

The clean_field check is called fairly late (after the field's clean method for example), but as long as you do not try to perform that validation check earlier it should work fine.

Of course you can also do the camelcase conversion first and the equality check after if you like to, it doens't really matter.


If you need to go from ALLCAPS to CapCase, the short answer is no.

How would your system know that Aaaaaaaaaa should be capitalized AaaaAaaaAa?

0

精彩评论

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

关注公众号