将所有CharField表单字段输入转换为Django表单中的小写字母 [英] Convert all CharField Form Field inputs to lowercase in Django forms

查看:47
本文介绍了将所有CharField表单字段输入转换为Django表单中的小写字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Django表单进行用户注册,用户可以在其中输入优惠券代码.我希望在优惠券代码字段中输入的所有字符都将转换为小写.我曾尝试在save方法,自定义清理方法和自定义验证器中使用.lower(),但是这些方法没有运气.下面是我的代码.

I am using a Django form for user signup, where the user is able to enter a coupon code. I want all characters entered in the coupon code field to be converted to lowercase. I've tried using .lower() in the save method, in a custom cleaning method, and in a custom validator, but am having no luck with those approaches. Below is my code.

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

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

As mentioned above, I've also tried a cleaning method, but this doesn't work either:

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

推荐答案

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

The solution is to create a custom form field, which allows you to override the to_python method, in which the raw values from the form fields can then be modified.

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>")
    )

这篇关于将所有CharField表单字段输入转换为Django表单中的小写字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆