python - 在 Django 表单中将所有 CharField 表单字段输入转换为小写

标签 python django python-2.7

我正在使用 Django 表单进行用户注册,用户可以在其中输入优惠券代码。我希望在优惠券代码字段中输入的所有字符都转换为小写。我试过在保存方法、自定义清理方法和自定义验证器中使用 .lower(),但我对这些方法并不满意。下面是我的代码。

class StripeSubscriptionSignupForm(forms.Form):
    coupon = forms.CharField(max_length=30,
        required=False,
        validators=[validate_coupon],
        label=mark_safe("<p class='signup_label'>Promo Code</p>")

    def save(self, user):
        try:
            customer, created = Customer.get_or_create(user)
            customer.update_card(self.cleaned_data["stripe_token"])
            customer.subscribe(self.cleaned_data["plan"], self.cleaned_data["coupon"].lower())
        except stripe.StripeError as e:
            # handle error here
            raise e

如前所述,我也尝试过一种清洁方法,但这也不起作用:

def clean_coupon(self):
    return self.cleaned_data['coupon'].lower()

最佳答案

解决方案是创建一个自定义表单字段,它允许您覆盖 to_python 方法,然后可以修改表单字段中的原始值。

class CouponField(forms.CharField):
    def to_python(self, value):
        return value.lower()


class StripeSubscriptionSignupForm(forms.Form):
    coupon = CouponField(max_length=30,
        required=False,
        validators=[validate_coupon],
        label=mark_safe("<p class='signup_label'>Promo Code</p>")
    )

关于python - 在 Django 表单中将所有 CharField 表单字段输入转换为小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24313201/

相关文章:

python - MatrixSymbol 中的 Sympy 下划线以 pretty-print 方式更改外观

python - 我可以使用 ctypes 从 C 中嵌入的 python 回调 C 函数吗?

python - python逐行读取.xls文件数据

python - 调用python 2.7打开python 2.4

python - 编写与python2和python3兼容的代码是使用 __future__ 还是 future 更可取?

c# - 导出使用 scikit-learn 库创建的 "RandomForestRegressor"模型

python - 将列添加到数据框中,根据 python 中的列数据类型显示 bool 值

python - Python 中的 H2OFrame() 正在向 Pandas DataFrame 添加额外的重复行 - Bug?

django - 无法分配 '1' : Comment. 用户必须是用户实例

python - django makemigrations 覆盖以创建具有自定义名称的迁移文件