class TeacherForm(Form): Teacher_name = fields.CharField(error_messages={'required': '您输入的格式不正确,请重新输入'}) sex = fields.IntegerField(widget=widgets.Select(choices=Teacher.choise)) age = fields.IntegerField()
class TestForm(Form): text = fields.CharField() email = fields.EmailField() value = fields.IntegerField() single = fields.ChoiceField(choices=TestChoices) multi = fields.MultipleChoiceField(choices=TestChoices)
class EditActionOperationForm(forms.Form): """编辑报警动作表单验证类""" name = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='报警动作名称', help_text='必填项', widget=widgets.TextInput( attrs={'class': 'form-control'} ) ) action_type = fields.CharField( error_messages={'invalid': '格式错误'}, label='动作类型', help_text='必填项', widget=widgets.Select( choices=[('email', '邮件'), ('sms', '短信'), ('weixin', '微信'), ('script', '脚本')], attrs={'class': 'form-control'} ) ) step = fields.IntegerField( error_messages={ 'required': '不能为空', 'invalid': '格式错误', }, label='报警升级阈值', help_text='必填项', widget=widgets.NumberInput( attrs={'class': 'form-control'} ) ) user_profile_id = fields.MultipleChoiceField( required=False, error_messages={'invalid': '格式错误'}, label='所属用户', choices=[], widget=widgets.SelectMultiple( attrs={'class': 'form-control', 'size': 10} ) ) script_name = fields.CharField( required=False, max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='脚本名称', widget=widgets.TextInput( attrs={'class': 'form-control'} ) ) memo = fields.CharField( required=False, error_messages={ 'invalid': '格式错误', }, label='备注', widget=widgets.Textarea( attrs={'class': 'form-control'} ) ) def __init__(self, *args, **kwargs): super(EditActionOperationForm, self).__init__(*args, **kwargs) self.aid = self.initial['aid'] action_operation_obj = models.ActionOperation.objects.filter(id=self.aid).first() self.fields['name'].initial = action_operation_obj.name self.fields['action_type'].initial = action_operation_obj.action_type self.fields['step'].initial = action_operation_obj.step self.fields['user_profile_id'].choices = models.UserProfile.objects.values_list('id', 'email') self.fields['user_profile_id'].initial = [] query_set = models.ActionOperation.objects.filter(id=self.aid).values('user_profiles__id') for item in query_set: self.fields['user_profile_id'].initial.append(item['user_profiles__id']) self.fields['script_name'].initial = action_operation_obj.script_name self.fields['memo'].initial = action_operation_obj.memo def clean_name(self): name = self.cleaned_data.get('name') count = models.ActionOperation.objects.exclude(id=self.aid).filter(name=name).count() if count: raise ValidationError(_('报警动作%(name)s已存在'), code='invalid', params={'name': name}) else: return self.cleaned_data.get('name')
class TestFormWithoutRequiredField(Form): number = fields.IntegerField(required=False)
class ServerEditForm(forms.ModelForm): # def __init__(self,*args,**kwargs): # self.create_by = kwargs.pop('create_by') # super(ServerEditForm,self).__init__(*args,**kwargs) name = fields.CharField( label="资产名称", error_messages={'required': '资产名称不能为空'}, widget=widgets.Input(attrs={'class': "form-control"})) ip = fields.GenericIPAddressField( label="IP地址", error_messages={'required': 'IP地址不能为空'}, widget=widgets.Input( attrs={ 'class': 'form-control', 'data-inputmask': "'alias': 'ip'", 'data-mask': '' })) ssh_port = fields.IntegerField( label="SSH 端口", widget=widgets.Input(attrs={'class': 'form-control'})) ip2 = fields.GenericIPAddressField( label="公网IP地址", required=False, widget=widgets.Input( attrs={ 'class': 'form-control', 'data-inputmask': "'alias': 'ip'", 'data-mask': '' })) class Meta: model = Server # exclude = ('create_by') fields = [ 'name', 'ip', 'project', 'label', 'is_active', 'idc_name', 'ssh_user', 'ssh_port', 'ip2', 'comment' ] widgets = { 'project': forms.SelectMultiple(attrs={ 'class': 'form-control select2', 'data-placeholder': '业务组' }), 'label': forms.SelectMultiple(attrs={ 'class': 'form-control select2', 'data-placeholder': '标签' }), 'idc_name': forms.Select(attrs={'class': 'form-control select2'}), 'ssh_user': forms.SelectMultiple(attrs={ 'class': 'form-control select2', 'data-placeholder': '用户' }), 'comment': forms.Textarea(attrs={'class': 'form-control'}), } help_texts = { 'name': '* required', 'ip': '* required', 'port': '* required', }
class ArtistForm(Form): name = fields.CharField(required=True, max_length=100) genres = FieldList(field=fields.CharField(max_length=30)) members = fields.IntegerField()
class HostForm(Form): hostname = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) ecsname = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) login_port = fields.IntegerField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) cpu = fields.IntegerField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) mem = fields.IntegerField( # 存入的类型不一样,所以这里要 IntagerField required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) speed = fields.IntegerField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) eth1_network = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) eth0_network = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) sn = fields.CharField(required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) kernel = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) remarks = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) createtime = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) expirytime = fields.CharField( required=True, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' })) state = fields.IntegerField( required=True, min_value=1, max_value=4, # 允许输入的值,最为1,最大为4 widget=widgets.TextInput(attrs={ 'class': 'form-control', 'style': 'color: green;' }), ) # ForeignKey # state_id = fields.ChoiceField( # required= True, # choices=[], # widget = widgets.Select(attrs={'class': 'form-control'}) # ) lab_id = fields.ChoiceField( required=True, choices=[], widget=widgets.Select(attrs={ 'class': 'form-control', 'style': 'color: green;' })) os_id = fields.ChoiceField( required=True, choices=[], widget=widgets.Select(attrs={ 'class': 'form-control', 'style': 'color: green;' })) source_id = fields.ChoiceField( required=True, choices=[], widget=widgets.Select(attrs={ 'class': 'form-control', 'style': 'color: green;' })) region_id = fields.ChoiceField( # 一对多的 region_id 字段不加_id 时会报错 required= True, # 因为 fields.CharField 渲染的input的框是,输入的都是str()类型,ID 又是唯一的所有这里 choices=[], # 所有插数据的时候 str() 和int() 数据类型不一样会报错 # choices = models.Region.objects.values_list('id','name'), # values_list这里取到的还是int() # values_list 通过这个方法可以拿到元组 即 ('id','name') # form.cleaned_data['region'] = int(form.cleaned_data['region']) # 可以这么理解。但是最好别这样用,一对多数据多了的时候 就很麻烦 # 所有最好的方法就是 在source 后面 加个 _id 即可 -> source_id 插入数据时就不会报错 widget=widgets.Select(attrs={ 'class': 'form-control', 'style': 'color: green;' }) # 加样式是 通过 form-control 修改 ) #login_port = fields.CharField() M2M 没写 def __init__(self, *args, **kwargs): super(HostForm, self).__init__( *args, **kwargs) # 先执行 父类的 __init__方法,也就是 View类的__init__方法 # self.fields['state_id'].choices = models.Host.objects.values_list('id', 'state_choices') self.fields['lab_id'].choices = models.Lable.objects.values_list( 'id', 'name') # 列表 self.fields['os_id'].choices = models.Os.objects.values_list( 'id', 'name') self.fields['source_id'].choices = models.Source.objects.values_list( 'id', 'name') self.fields['region_id'].choices = models.Region.objects.values_list( 'id', 'name')
class AddressForm(DialogModelForm): field_css_classes = { '*': getattr(Bootstrap3ModelForm, 'field_css_classes'), 'zip_code': ['has-feedback', 'form-group', 'frmgrp-zip_code'], 'location': ['has-feedback', 'form-group', 'frmgrp-location'], 'street_name': ['has-feedback', 'form-group', 'frmgrp-street_name'], 'street_number': ['has-feedback', 'form-group', 'frmgrp-street_number'], } priority = fields.IntegerField(widget=widgets.HiddenInput()) # TODO: use a choice field for selection class Meta: model = AddressModel exclude = ('customer', 'priority_shipping', 'priority_billing',) def __init__(self, initial=None, instance=None, *args, **kwargs): if instance: initial = initial or {} initial['priority'] = getattr(instance, self.priority_field) super(AddressForm, self).__init__(initial=initial, instance=instance, *args, **kwargs) @classmethod def get_model(cls): return cls.Meta.model @classmethod def form_factory(cls, request, data, cart): """ From the given request, update the database model. If the form data is invalid, return an error dictionary to update the response. """ # search for the associated address DB instance or create a new one priority = data and data.get('priority') or 0 filter_args = {'customer': request.customer, cls.priority_field: priority} instance = cls.get_model().objects.filter(**filter_args).first() address_form = cls(data=data, instance=instance) if address_form.is_valid(): if not instance: instance = address_form.save(commit=False) instance.customer = request.customer setattr(instance, cls.priority_field, priority) assert address_form.instance == instance instance.save() cls.set_address(cart, instance) else: return {address_form.form_name: dict(address_form.errors)} @classmethod def get_max_priority(cls, customer): """ Return the maximum priority for this address model. """ aggr = cls.get_model().objects.filter(customer=customer).aggregate(Max(cls.priority_field)) return aggr.get('{}__max'.format(cls.priority_field, 0)) @classmethod def set_address(cls, cart, instance): # TODO: method must be connected to allow different priorities address_form = cls(instance=instance) data = address_form.initial data.pop('id', None) data.initial.pop('priority', None) data.update({'customer': cart.customer, '{}__isnull'.format(cls.priority_field): False}) instance, created = cls.get_model().objects.get_or_create(**data) if created: instance.priority_billing = cls.get_max_priority(cart.customer) + 1 instance.save()
class SystempayPaymentForm(SystempayBaseForm): vads_amount = fields.IntegerField(widget=forms.HiddenInput()) vads_currency = fields.IntegerField(widget=forms.HiddenInput()) vads_ext_info_type = fields.CharField(widget=forms.HiddenInput()) vads_page_action = fields.CharField(initial="PAYMENT", widget=forms.HiddenInput()) vads_payment_config = fields.CharField(initial="SINGLE", widget=forms.HiddenInput()) vads_capture_delay = fields.IntegerField(initial=0, widget=forms.HiddenInput()) vads_validation_mode = fields.IntegerField(initial=0, widget=forms.HiddenInput()) @classmethod def get_form_for_transaction(cls, transaction, sp_config): person_id = ( str(transaction.payment.person.pk) if transaction.payment.person else "anonymous" ) success_url = front_url("payment_return", kwargs={"pk": transaction.payment_id}) failure_url = front_url( f"{transaction.payment.mode}:failure", kwargs={"pk": transaction.pk} ) form = cls( initial={ "vads_site_id": sp_config["site_id"], "vads_ctx_mode": "PRODUCTION" if sp_config["production"] else "TEST", "vads_currency": sp_config["currency"], "vads_order_id": transaction.pk, "vads_trans_id": get_trans_id_from_order_id(transaction.pk), "vads_trans_date": transaction.created.strftime("%Y%m%d%H%M%S"), "vads_amount": transaction.payment.price, "vads_cust_email": transaction.payment.email, "vads_cust_id": person_id, "vads_cust_first_name": transaction.payment.first_name, "vads_cust_last_name": transaction.payment.last_name, "vads_cust_address": ", ".join( [ transaction.payment.location_address1, transaction.payment.location_address2, ] ), "vads_cust_zip": transaction.payment.location_zip, "vads_cust_city": transaction.payment.location_city, "vads_cust_state": transaction.payment.location_state, "vads_cust_country": transaction.payment.location_country, "vads_ext_info_type": transaction.payment.type, "vads_url_success": success_url, **{ f"vads_url_{status}": f"{failure_url}?status={status}" for status in ["cancel", "error", "refused"] }, } ) if transaction.payment.phone_number: if ( phonenumberutil.number_type(transaction.payment.phone_number) == PhoneNumberType.MOBILE ): form.add_field( "vads_cust_cell_phone", transaction.payment.phone_number.as_e164 ) else: form.add_field( "vads_cust_phone", transaction.payment.phone_number.as_e164 ) for key in transaction.payment.meta: form.add_field("vads_ext_info_meta_" + key, transaction.payment.meta[key]) form.update_signature(sp_config["certificate"]) return form
class ArticlesAddForm(dform.Form): # 项目添加 custom_id = fields.IntegerField( label='客户名称', label_suffix=":", widget=widgets.Select(attrs={'class': 'form-control'})) product_id = fields.IntegerField( label='业务品种', label_suffix=":", widget=widgets.Select(attrs={'class': 'form-control'})) renewal = fields.FloatField( label='续贷金额(元)', label_suffix=":", widget=widgets.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '输入续贷金额' })) augment = fields.FloatField( label='新增金额(元)', label_suffix=":", widget=widgets.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '输入新增金额' })) credit_term = fields.IntegerField( label='授信期限(月)', label_suffix=":", initial=12, widget=widgets.NumberInput(attrs={ 'class': 'form-control', 'placeholder': '输入授信期限(月)' })) process_id = fields.IntegerField( label="审批流程", label_suffix=":", widget=widgets.Select(attrs={'class': 'form-control'})) director_id = fields.IntegerField( label="项目经理", label_suffix=":", widget=widgets.Select(attrs={'class': 'form-control'})) assistant_id = fields.IntegerField( label="项目助理", label_suffix=":", widget=widgets.Select(attrs={'class': 'form-control'})) control_id = fields.IntegerField( label="风控专员", label_suffix=":", widget=widgets.Select(attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): super(ArticlesAddForm, self).__init__(*args, **kwargs) self.fields[ 'custom_id'].widget.choices = models.Customes.objects.values_list( 'id', 'name') self.fields[ 'product_id'].widget.choices = models.Product.objects.values_list( 'id', 'name') self.fields[ 'process_id'].widget.choices = models.Process.objects.values_list( 'id', 'name') self.fields[ 'director_id'].widget.choices = models.Employees.objects.filter( job__name='项目经理', employee_status=1).values_list('id', 'name') self.fields[ 'assistant_id'].widget.choices = models.Employees.objects.filter( job__name='项目经理', employee_status=1).values_list('id', 'name') self.fields[ 'control_id'].widget.choices = models.Employees.objects.filter( job__name='风控专员', employee_status=1).values_list('id', 'name')
class SolvePlanForm(forms.Form): trouble_id = fields.IntegerField( required=False, widget=widgets.TextInput(attrs={"type": 'hidden'})) evaluate = fields.CharField( required=True, widget=widgets.Select(choices=models.Trouble.evaluate_choices))
class PKeyQuerySetForm(forms.QuerySetForm): pk = fields.IntegerField()
class CreateBussiness(forms.Form): """业务验证""" business_chooics = fields.ChoiceField( choices=models.Bussiness.business_type, label="业务线", required=True, error_messages={"required": "此选项必填"}, widget=widgets.Select(attrs={'class': 'form-control'})) virIP = fields.GenericIPAddressField( required=True, label="业务IP", widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={ 'required': "此项不能为空", 'invalid': '请输入正确的IP格式' }) application = fields.CharField( required=True, label="业务名称", widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={ 'required': "此项不能为空", }) port = fields.IntegerField( required=False, label="业务端口", widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={'invalid': '请输入正确的端口格式'}) component = fields.CharField( required=True, label="业务用途", min_length=5, max_length=120, widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={ 'required': '此项不能为空', 'min_length': '不能少于5个字符', 'max_length': '不能超过20个字符' }) principal = fields.CharField( required=True, label="负责人", widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={ 'required': '此项不能为空', }) note = fields.CharField( required=False, label="备注", max_length="10", widget=widgets.TextInput(attrs={'class': 'form-control'}), error_messages={"max_length": "最大不超过10个字符"}) def clean_business_chooics(self): """选择业务线验证""" value = self.cleaned_data.get('business_chooics') if value == '0': raise ValidationError("请选择业务线") return value
class Student_to_teacher(dforms.Form): e_id = fields.CharField( required=True, label='ID', error_messages={}, widget=widgets.TextInput(attrs={'class': 'form-control'})) e_ttos_evaluate = fields.CharField( required=False, label='老师对学生评价', widget=widgets.TextInput(attrs={'class': 'form-control'})) e_stot_evaluate = fields.CharField( required=False, label='学生对老师评价', widget=widgets.TextInput(attrs={'class': 'form-control'})) e_ttos_score = fields.IntegerField( required=False, label='老师对学生的打分', widget=widgets.TextInput(attrs={'class': 'form-control'})) e_stot_score = fields.IntegerField( required=False, label='学生对老师的打分', widget=widgets.TextInput(attrs={'class': 'form-control'})) e_remark = fields.CharField( required=False, label='备注', widget=widgets.TextInput(attrs={'class': 'form-control'})) e_create_time = fields.IntegerField( required=True, label='创建时间', widget=widgets.TextInput(attrs={'class': 'form-control'})) e_tid = fields.IntegerField( required=False, widget=widgets.Select(attrs={'class': 'form-control'}), label='老师姓名', ) e_sid = fields.IntegerField( required=False, widget=widgets.Select(attrs={'class': 'form-control'}), label='学生姓名', ) e_did = fields.IntegerField( required=False, widget=widgets.Select(attrs={'class': 'form-control'}), label='节课程名称', ) def __init__(self, *args, **kwargs): super(Student_to_teacher, self).__init__(*args, **kwargs) self.fields[ 'e_tid'].widget.choices = models.WebTeacher.objects.values_list( 't_id', 't_name') self.fields[ 'e_sid'].widget.choices = models.WebStudent.objects.values_list( 's_id', 's_name') self.fields[ 'e_did'].widget.choices = models.WebDetail.objects.values_list( 'd_id', 'd_name')
class BaseForm(forms.Form): username = fields.CharField(max_length=32, ) age = fields.IntegerField( min_value=0, max_value=100, )
class SystempayBaseForm(forms.Form): form_action = "https://paiement.systempay.fr/vads-payment/" vads_site_id = fields.IntegerField(widget=forms.HiddenInput()) vads_ctx_mode = fields.CharField(widget=forms.HiddenInput()) vads_action_mode = fields.CharField( initial="INTERACTIVE", widget=forms.HiddenInput() ) vads_version = fields.CharField(initial="V2", widget=forms.HiddenInput()) vads_order_id = fields.CharField(widget=forms.HiddenInput()) vads_trans_id = fields.CharField(widget=forms.HiddenInput()) vads_trans_date = fields.CharField(widget=forms.HiddenInput()) vads_url_cancel = fields.CharField( initial=front_url_lazy("system_pay:return", query={"status": "cancel"}), widget=forms.HiddenInput(), ) vads_url_error = fields.CharField( initial=front_url_lazy("system_pay:return", query={"status": "error"}), widget=forms.HiddenInput(), ) vads_url_refused = fields.CharField( initial=front_url_lazy("system_pay:return", query={"status": "refused"}), widget=forms.HiddenInput(), ) vads_url_success = fields.CharField( initial=front_url_lazy("system_pay:return", query={"status": "success"}), widget=forms.HiddenInput(), ) vads_redirect_success_timeout = fields.CharField( initial=8, widget=forms.HiddenInput() ) vads_redirect_error_timeout = fields.CharField( initial=8, widget=forms.HiddenInput() ) vads_cust_email = fields.EmailField(widget=forms.HiddenInput()) vads_cust_id = fields.UUIDField(widget=forms.HiddenInput()) vads_cust_status = fields.CharField(initial="PRIVATE", widget=forms.HiddenInput()) vads_cust_first_name = fields.CharField(widget=forms.HiddenInput()) vads_cust_last_name = fields.CharField(widget=forms.HiddenInput()) vads_cust_address = fields.CharField(widget=forms.HiddenInput()) vads_cust_zip = fields.CharField(widget=forms.HiddenInput()) vads_cust_city = fields.CharField(widget=forms.HiddenInput()) vads_cust_country = fields.CharField(widget=forms.HiddenInput()) vads_cust_state = fields.CharField(widget=forms.HiddenInput()) signature = fields.CharField(widget=forms.HiddenInput()) def add_field(self, name, value): if value is None: return self.fields[name] = forms.CharField(initial=value, widget=forms.HiddenInput()) def update_signature(self, certificate): data = { field: str(self.get_initial_for_field(self.fields[field], field)) for field in self.fields.keys() } self.fields["signature"].initial = get_signature(data, certificate) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # SystemPay a des maximums de longueur pour chacun des ces champs trans_table = str.maketrans("", "", "<>") for f, l in { "vads_cust_first_name": 63, "vads_cust_last_name": 63, "vads_cust_address": 255, "vads_cust_zip": 64, "vads_cust_city": 128, "vads_cust_state": 127, }.items(): if self.get_initial_for_field(self.fields[f], f): self.initial[f] = self.get_initial_for_field( self.fields[f], f ).translate(trans_table)[:l]
class AddDBAccount(forms.Form): port = fields.IntegerField( required=True, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': 'input port'}), error_messages={'required': 'Port不能为空', }, ) comment = fields.CharField( required=False, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': '使用说明,少于20个字符'}), max_length=50, strip=True, error_messages={'max_length': '使用说明,少于20个字符'} ) normal_db_account = fields.CharField( required=False, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': '用户名为4-30个字符'}), min_length=4, max_length=30, strip=True, error_messages={'required': '标题不能为空', 'min_length': '用户名最少为4个字符', 'max_length': '用户名最不超过为30个字符'}, ) normal_db_password = fields.CharField( widget=widgets.PasswordInput(attrs={'class': "form-control", 'placeholder': '请输入密码,必须包含数字,字母,特殊字符'}, render_value=True), required=False, min_length=8, max_length=30, strip=True, validators=[ # 下面的正则内容一目了然,我就不注释了 RegexValidator(r'([^a-z0-9A-Z])+', '必须包含特殊字符'), RegexValidator(r'[A-Z]+', '必须包含da字母'), RegexValidator(r'[a-z]+', '必须包含x字母'), # RegexValidator(r' ', '密码不能包含空白字符'), RegexValidator(r'[0-9]+', '必须包含数字'), ], # 用于对密码的正则验证 error_messages={'required': '密码不能为空!', 'min_length': '密码最少为8个字符', 'max_length': '密码最多不超过为30个字符!', }, ) normal_db_password_again = fields.CharField( # render_value会对于PasswordInput,错误是否清空密码输入框内容,默认为清除,我改为不清楚 widget=widgets.PasswordInput(attrs={'class': "form-control", 'placeholder': '请再次输入密码!'}, render_value=True), required=False, strip=True, error_messages={ 'required': '请再次输入密码!', } ) admin_db_account = fields.CharField( required=False, widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': '用户名为4-30个字符'}), min_length=4, max_length=30, strip=True, error_messages={'required': '标题不能为空', 'min_length': '用户名最少为4个字符', 'max_length': '用户名最不超过为30个字符'}, ) admin_db_password = fields.CharField( widget=widgets.PasswordInput(attrs={'class': "form-control", 'placeholder': '请输入密码,必须包含数字,字母,特殊字符'}, render_value=True), required=False, min_length=8, max_length=30, strip=True, validators=[ # 下面的正则内容一目了然,我就不注释了 RegexValidator(r'([^a-z0-9A-Z])+', '必须包含特殊字符'), RegexValidator(r'[A-Z]+', '必须包含大写字母'), RegexValidator(r'[a-z]+', '必须包含小写字母'), # RegexValidator(r' ', '密码不能包含空白字符'), RegexValidator(r'[0-9]+','必须包含数字'), ], # 用于对密码的正则验证 error_messages={'required': '密码不能为空!', 'min_length': '密码最少为8个字符', 'max_length': '密码最多不超过为30个字符!', }, ) admin_db_password_again = fields.CharField( # render_value会对于PasswordInput,错误是否清空密码输入框内容,默认为清除,我改为不清楚 widget=widgets.PasswordInput(attrs={'class': "form-control", 'placeholder': '请再次输入密码!'}, render_value=True), required=False, strip=True, error_messages={'required': '请再次输入密码!', } ) def clean_username(self): # 对username的扩展验证,查找用户是否已经存在 username = self.cleaned_data.get('username') # users = models.User.objects.filter(username=username).count() # if users: # raise ValidationError('用户已经存在!') return username def _clean_new_password2(self): # 查看两次密码是否一致 password1 = self.cleaned_data.get('normal_db_password') password2 = self.cleaned_data.get('normal_db_password_again') if password1 != password2: # self.error_dict['pwd_again'] = '两次密码不匹配' # raise ValidationError('两次密码不匹配!') self.add_error('normal_db_password_again', '两次密码不匹配') password3 = self.cleaned_data.get('admin_db_password') password4 = self.cleaned_data.get('admin_db_password_again') if password3 != password4: # self.error_dict['pwd_again'] = '两次密码不匹配' self.add_error('admin_db_password_again','两次密码不匹配') # raise ValidationError(('两次密码不匹配!'), # code = 'error4' # ) def check_data(self): if len(self.cleaned_data['normal_db_account']) == 0 and len(self.cleaned_data['admin_db_account']) == 0: raise ValidationError(('Normal用户和admin用户至少有一个,不能全为空')) def clean(self): # 是基于form对象的验证,字段全部验证通过会调用clean函数进行验证 self._clean_new_password2() # 简单的调用而已 self.check_data()
class SystempayNewSubscriptionForm(SystempayBaseForm): vads_page_action = fields.CharField( initial="REGISTER_SUBSCRIBE", widget=forms.HiddenInput() ) vads_sub_amount = fields.IntegerField(widget=forms.HiddenInput()) vads_sub_effect_date = fields.CharField(widget=forms.HiddenInput()) vads_sub_currency = fields.IntegerField(widget=forms.HiddenInput()) vads_sub_desc = fields.CharField(widget=forms.HiddenInput()) @classmethod def get_form_for_transaction(cls, transaction, sp_config): person = transaction.subscription.person success_url = front_url( "subscription_return", kwargs={"pk": transaction.subscription_id} ) failure_url = front_url( f"{transaction.subscription.mode}:failure", kwargs={"pk": transaction.pk} ) person_data = {} if person is not None: person_data.update( { f.name: getattr(person, f.name) for f in person._meta.get_fields() if not f.is_relation } ) person_data.update(transaction.subscription.meta) form = cls( initial={ "vads_site_id": sp_config["site_id"], "vads_ctx_mode": "PRODUCTION" if sp_config["production"] else "TEST", "vads_sub_currency": sp_config["currency"], "vads_order_id": transaction.pk, "vads_trans_id": get_trans_id_from_order_id(transaction.pk), "vads_trans_date": transaction.created.strftime("%Y%m%d%H%M%S"), "vads_sub_effect_date": transaction.created.strftime("%Y%m%d"), "vads_sub_amount": transaction.subscription.price, "vads_cust_email": person.email, "vads_cust_id": transaction.subscription.person_id, "vads_cust_first_name": person_data.get("first_name"), "vads_cust_last_name": person_data.get("last_name"), "vads_cust_address": ", ".join( [ person_data.get("location_address1", ""), person_data.get("location_address2", ""), ] ).strip(), "vads_cust_zip": person_data.get("location_zip"), "vads_cust_city": person_data.get("location_city"), "vads_cust_state": person_data.get("location_state"), "vads_cust_country": person_data.get("location_country"), "vads_sub_desc": get_recurrence_rule(transaction.subscription), "vads_url_success": success_url, **{ f"vads_url_{status}": f"{failure_url}?status={status}" for status in ["cancel", "error", "refused"] }, } ) form.update_signature(sp_config["certificate"]) return form
class PackageBind(forms.Form): package_id = fields.IntegerField(error_messages={ 'required': '套餐ID不能为空', 'invalid': '套餐ID必须为数字' })
class QuantityMixin(EntangledModelFormMixin): quantity = fields.IntegerField() class Meta: entangled_fields = {'properties': ['quantity']}
class TestFormWithRequiredField(Form): number = fields.IntegerField(required=True)
class FilterInquiryByQuestionForm(FilterInquiriesMixin, FilterFormBase): description = "Filter by question" num_questions = fields.IntegerField(initial=0, widget=widgets.HiddenInput) prefix = 'filter_q' def __init__(self, *args, filter_models=None, **kwargs): super(FilterInquiryByQuestionForm, self).__init__(*args, **kwargs) self.filter_models = filter_models if self.filter_models: if len(self.filter_models) == 0: # An attribute used in the view to say that it is not used and thus should not be shown # This is the case when there are no related filters set self.not_used = True else: i = 0 for filter_instance in self.filter_models: self.create_fields_for_instance(i, filter_instance) i += 1 self.fields['num_questions'].initial = len(filter_models) elif self.is_bound: self.create_fields_from_data() def create_fields_for_instance(self, index, filter_instance: QuestionFilter) -> None: # Make sure to hide the question widget, it is only to communicate between the originating view and the # Chart target view question_filter_field = fields.IntegerField(initial=filter_instance.id, widget=widgets.HiddenInput) if filter_instance.question.question_type == Question.TYPE_CHOICE: # Multiple choice question, get the answers and set the field choices = [(-1, '---')] for answer in filter_instance.question.answeroption_set.order_by("value"): # Make sure to call answer.value, it is the value that it is stored as on the db. choices.append((answer.value, answer.answer)) answer_field = fields.ChoiceField(choices=choices, initial=-1) elif filter_instance.question.question_type == Question.TYPE_OPEN: answer_field = fields.CharField(required=False) else: # There is no code implemented for this kind of question, so just return return answer_field.label = filter_instance.question.name self.fields[f'questionfilter_{index}'] = question_filter_field self.fields[f'answer_{index}'] = answer_field def create_fields_from_data(self): # Get the amount of filters that need to be loaded try: field = self.fields['num_questions'] value = field.widget.value_from_datadict( self.data, self.files, self.add_prefix('num_questions') ) value = field.clean(value) except ValidationError: return # Loop over all fields for i in range(value): self.fields[f'questionfilter_{i}'] = fields.IntegerField(initial=-1) self.fields[f'answer_{i}'] = fields.CharField() def filter(self, data): data = super(FilterInquiryByQuestionForm, self).filter(data) for i in range(self.cleaned_data['num_questions']): # Filter for the specific question question_filter = QuestionFilter.objects.get(id=self.cleaned_data[f'questionfilter_{i}']) answer = self.cleaned_data[f'answer_{i}'] if question_filter.question.question_type == Question.TYPE_CHOICE: # -1 is the default no answer value if answer != "-1": data = data.filter( inquiryquestionanswer__question=question_filter.question, inquiryquestionanswer__answer=answer ) elif question_filter.question.question_type == Question.TYPE_OPEN: if len(answer) > 0: data = data.filter( inquiryquestionanswer__question=question_filter.question, inquiryquestionanswer__answer__icontains=answer ) return data @classmethod def can_filter(cls, filter_models=None, **init_kwargs): if filter_models is not None: return len(filter_models) > 0 return super(FilterInquiryByQuestionForm, cls).can_filter(**init_kwargs)
class TestFormWithNonRequiredFields(Form): number = fields.IntegerField(required=False) name = fields.CharField(required=False, empty_value=None)
class LoginForm(BaseForm, django_forms.Form): # username = django_fields.CharField( # min_length=6, # max_length=20, # error_messages={'required': '用户名不能为空.', 'min_length': "用户名长度不能小于6个字符", 'max_length': "用户名长度不能大于32个字符"} # ) username = django_fields.CharField( error_messages={'required': '用户名不能为空.'}, widget=django_widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入登录账户", }), label='用户名', ) # password = django_fields.RegexField( # '^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$\%\^\&\*\(\)])[0-9a-zA-Z!@#$\%\^\&\*\(\)]{8,32}$', # min_length=12, # max_length=32, # error_messages={'required': '密码不能为空.', # 'invalid': '密码必须包含数字,字母、特殊字符', # 'min_length': "密码长度不能小于8个字符", # 'max_length': "密码长度不能大于32个字符"} # ) password = django_fields.CharField( error_messages={'required': '密码不能为空.'}, widget=django_widgets.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': '请输入登录密码', }, render_value=True, ), label='密码', ) rmb = django_fields.IntegerField(required=False) check_code = django_fields.CharField( error_messages={'required': '验证码不能为空.'}, widget=django_widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入验证码" }), label='验证码', ) # def clean_check_code(self): # if self.request.session.get('CheckCode').upper() != self.request.POST.get('check_code').upper(): # raise ValidationError(message='验证码错误', code='invalid') # # # # else: # # return self.changed_data['check_code'] def clean_check_code(self): if self.request.session.get('CheckCode').upper( ) != self.request.POST.get('check_code').upper(): raise ValidationError(message='验证码错误', code='invalid') else: return self.request.session.get('CheckCode') def clean_username(self): v = self.cleaned_data.get('username') if not models.UserInfo.objects.filter(username=v).count(): raise ValidationError("用户名不存在") return v def clean_password(self): v = self.cleaned_data.get('password') if not models.UserInfo.objects.filter(password=v).count(): raise ValidationError("密码不存在") return v
class AddChartForm(forms.Form): """创建图表表单验证类""" name = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='图表名', help_text='必填项', widget=widgets.TextInput(attrs={'class': 'form-control'})) chart_type = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='图表类型', help_text='必填项', widget=widgets.Select(choices=[('line', '线型图'), ('area', '面积图'), ('pie', '饼图')], attrs={'class': 'form-control'})) templates_id = fields.IntegerField(error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='模板', help_text='必填项', widget=widgets.Select( choices=[], attrs={'class': 'form-control'})) applications_id = fields.IntegerField(error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='应用集', help_text='必填项', widget=widgets.Select( choices=[], attrs={'class': 'form-control'})) item_id = fields.MultipleChoiceField( error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='监控项', help_text='必填项', choices=[], widget=widgets.SelectMultiple(attrs={ 'class': 'form-control', 'size': 10 })) auto = fields.CharField(required=False, error_messages={ 'invalid': '格式错误', }, label='是否自动', help_text='必填项', widget=widgets.CheckboxInput()) memo = fields.CharField( required=False, error_messages={ 'invalid': '格式错误', }, label='备注', widget=widgets.Textarea(attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): super(AddChartForm, self).__init__(*args, **kwargs) self.fields[ 'templates_id'].widget.choices = models.Template.objects.all( ).values_list('id', 'name') item_temp_list = models.Item.objects.values_list('id', 'name', 'key') item_list = [] for item in item_temp_list: item_list.append([item[0], '%s %s' % (item[1], item[2])]) self.fields['item_id'].choices = item_list def clean_name(self): name = self.cleaned_data.get('name') chart_obj = models.Chart.objects.filter(name=name).first() if chart_obj: raise ValidationError(_('图表%(name)s已存在'), code='invalid', params={'name': name}) else: return self.cleaned_data.get('name')
def build_integer_field(self, attr, **kwargs): """ Build field for sqlalchemy integer type. """ return djangofields.IntegerField(**kwargs)
class ApplicationEditForm(forms.Form): """编辑应用表单认证""" name = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='应用名称', help_text='必填', widget=widgets.TextInput(attrs={'class': 'form-control'})) path_name = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='应用目录名', help_text='必填', widget=widgets.TextInput(attrs={'class': 'form-control'})) ip = fields.GenericIPAddressField( error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='IP地址', help_text='必填', widget=widgets.TextInput(attrs={'class': 'form-control'})) project_id = fields.IntegerField(error_messages={ 'required': '不能为空', 'invalid': '格式错误' }, label='所属项目', help_text='必填', widget=widgets.Select( choices=[], attrs={'class': 'form-control'})) def __init__(self, *args, **kwargs): super(ApplicationEditForm, self).__init__(*args, **kwargs) self.aid = self.initial['aid'] application_obj = models.Application.objects.filter( id=self.aid).first() self.fields['name'].initial = application_obj.name self.fields['path_name'].initial = application_obj.path_name self.fields['ip'].initial = application_obj.ip self.fields['project_id'].widget.choices = list( models.Project.objects.values_list('id', 'name')) self.fields['project_id'].initial = [application_obj.project_id] def clean_name(self): name = self.cleaned_data.get('name') count = models.Application.objects.exclude(id=self.aid).filter( name=name).count() if count: raise ValidationError(_('应用名称[%(name)s]已存在'), code='invalid', params={'name': name}) return name def clean_project_id(self): project_id = self.cleaned_data.get('project_id') count = models.Project.objects.filter(id=project_id).count() if not count: raise ValidationError(_('所属项目[%(project_id)s]不存在'), code='invalid', params={'project_id': project_id}) return project_id
class RegisterForm(Form): """注册验证FORM""" username = fields.CharField( label="用户名:", widget=widgets.TextInput(attrs={ "id": "user", "class": "inputstyle2", "maxlength": "16" }), error_messages={"required": "用户名不能为空!"}) pwd = fields.CharField( label="密码:", widget=widgets.PasswordInput(attrs={ "id": "passwd", "class": "inputstyle2", "maxlength": "16" }), error_messages={"required": "密码不能为空!"}) pwd_again = fields.CharField( label="确认密码:", widget=widgets.PasswordInput(attrs={ "id": "passwd2", "class": "inputstyle2", "maxlength": "16" }), error_messages={"required": "确认密码不能为空!"}) qq = fields.IntegerField( label="QQ:", widget=widgets.TextInput(attrs={ "id": "qq", "class": "inputstyle2", "maxlength": "10" }), error_messages={ "required": "QQ号不能为空!", "invalid": "QQ号必须为数字!" }) def clean_username(self): """检测用户输入的用户名""" username = self.cleaned_data.get("username") user_obj = models.User.objects.filter(username=username).first() if user_obj: raise ValidationError("用户名已经存在!", "invalid") return username def clean_qq(self): """检测用户输入的qq号""" qq = self.cleaned_data.get("qq") user_obj = models.User.objects.filter(qq=qq).first() if user_obj: raise ValidationError("qq号已经存在!", "invalid") return qq def clean_pwd_again(self): """检测用户输入的密码""" pwd = self.cleaned_data.get("pwd") pwd_again = self.cleaned_data.get("pwd_again") if pwd != pwd_again: raise ValidationError("两次输入的密码不一样!", "invalid") return pwd_again
class AddTeacher(forms.Form): name = fields.CharField(widget=widgets.TextInput(attrs={ "class": "form-control ", "placeholder": "请输入姓名" }), ) username = fields.CharField( widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "请输入工号" }), ) gender = fields.CharField(widget=widgets.Select(choices=( ('M', '男'), ('F', '女'), ))) college = fields.IntegerField(widget=widgets.Select( attrs={"class": "form-control"}, choices=colleges)) place = fields.IntegerField( widget=widgets.Select(attrs={"class": "form-control"}, choices=[(1, '助教'), (2, '讲师'), ( 3, '高级讲师'), (4, '副教授'), (5, '教授'), ( 6, '高级教授'), (7, '特聘教授'), (8, '客座教授')])) province = fields.IntegerField(widget=widgets.Select( attrs={"class": "form-control"}, choices=provinces)) card_id = fields.CharField( widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "请输入18位身份证号", }), validators=[RegexValidator('^\d{17}[\w]$')]) nation = fields.CharField(widget=widgets.Select( attrs={"class": "form-control"}, choices=nations, )) email = fields.EmailField( required=False, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "请输入电子邮件" }), ) telephone = fields.CharField( required=False, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "请输入电话号" }), validators=[RegexValidator(r'\d{11}')]) qq = fields.CharField(required=False, widget=widgets.TextInput( attrs={"class": "form-control"}, ), validators=[RegexValidator('^\d{6,10}$')]) def __init__(self, *args, **kwargs): super(AddTeacher, self).__init__(*args, **kwargs) tno = User.objects.filter(role_id=2).last() if tno: tno = tno.username init_no = str(int(tno) + 1) self.fields["username"].initial = init_no
class ProjectInfoForm(Form): # project_id = fields.IntegerField( # widget=widgets.Select(choices=models.Project.objects.values_list('id', 'project_name').filter(), # attrs={'class': 'form-control'}) # ) project_id = fields.IntegerField(widget=widgets.Select( attrs={'class': 'form-control'})) # project_id = fields.CharField( # widget=widgets.TextInput(attrs={'class': 'form-control'}), # ) project_bios = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) project_mb = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) project_os = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) update_time = fields.DateTimeField(widget=widgets.TextInput( attrs={'class': 'form-control'})) dr_chipset = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_vga = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_iamt = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_storage = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_lan = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_audio = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_cr = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_wireless = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_bt = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_panel = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_finger_printer = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_g_sensor = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_camera = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_usb = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_com_parallel = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_serial_io = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_sgx = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) dr_others = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control'}), ) def __init__(self, *args, **kwargs): super(ProjectInfoForm, self).__init__(*args, **kwargs) self.fields[ "project_id"].widget.choices = models.Project.objects.values_list( "id", "project_name").filter()