我有一个简单的模型:
class Team(models.Model):
team_member_phone = models.CharField(max_length=128, default='',)
team_member_phone_clean = models.CharField(max_length=128, default='',)
一个简单的形式:
class TeamAddForm(forms.ModelForm):
class Meta:
model = Team
fields = ( 'team_member_phone')
用户可以+44 123 123 123
格式输入手机。
如何从+
中删除任何非数字字符(例如空格和team_member_phone
)并将结果存储在team_member_phone_clean
中?
我是否需要在提交表单时通过views.py
执行此操作,还是可以将其作为模型的一部分(最好)编写,因此它是动态生成的(即自动更新)?< / p>
注意,我想要两个版本,这样我就可以代表&#34;用户友好&#34;再次编辑数字时的空白格式。
答案 0 :(得分:1)
我会在模型中保存:
import re
class Team(models.Model):
team_member_phone = models.CharField(max_length=128, default='',)
team_member_phone_clean = models.CharField(max_length=128, default='',)
def set_member_phone_clean(self):
self.team_member_phone_clean = re.sub(r"(\s)|([^\d])", "", self.team_member_phone)
def save(self, *args, **kwargs):
self.set_member_phone_clean()
super(Team, self).save(*args, **kwargs)
答案 1 :(得分:0)
是的,您必须以TeamAddForm的形式定义它,当您检查form.is_valid()时会自动调用它,前提是您已覆盖表单的clean方法
def clean(self):
cleaned_data = super(TeamAddForm, self).clean()
# do your processing here with self.fields['team_member_phone'] and return back the data
return cleaned_data