class ArticleForm(forms.Form): title = fields.CharField( widget=widgets.TextInput( attrs={ "class": "form-control", "id": "title", "placeholder": "文章标题", }) ) summary = fields.CharField( widget=widgets.Textarea( attrs={ "class": "form-control", "id": "summary", "placeholder": "文章简介", "rows": "2", } ) ) content = fields.CharField( widget=widgets.Textarea( attrs={ "name": "content", "id": "content", "style": "width: 100%;min-height:500px;visibility:hidden;", } ) ) article_type_id = fields.ChoiceField( choices=[], widget=widgets.RadioSelect ) category_id = fields.ChoiceField( choices=[], widget=widgets.RadioSelect ) tags = fields.MultipleChoiceField( required=False, choices=[], widget=widgets.CheckboxSelectMultiple ) top = fields.MultipleChoiceField( required=False, choices=[("1", "置顶")], widget=widgets.CheckboxSelectMultiple ) def __init__(self, request, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) username = request.session.get("username", None) # 获取session中的用户名 user_obj = models.UserInfo.objects.filter(username=username).select_related("blog").first() # 获取用户对象 self.fields["article_type_id"].choices = models.ArticleType.objects.values_list("nid", "type") # 获取所有类型 self.fields["category_id"].choices = models.Category.objects.filter(blog_id=user_obj.blog.nid).values_list( "nid", "title" ) # 获取用户所有分类 self.fields["tags"].choices = models.Tag.objects.filter(blog_id=user_obj.blog.nid).values_list( "nid", "title" ) # 获取用户所有标签
from django import forms from django.forms import widgets from aspc.college.models import Building from aspc.housing.models import Review, Room, Suite from aspc.housing.forms.widgets import ColumnCheckboxSelectMultiple, RatingRadioFieldRenderer from django.utils.safestring import mark_safe from django.core.exceptions import ValidationError rating_widgets = { 'quiet': widgets.RadioSelect(renderer=RatingRadioFieldRenderer), 'spacious': widgets.RadioSelect(renderer=RatingRadioFieldRenderer), 'temperate': widgets.RadioSelect(renderer=RatingRadioFieldRenderer), 'maintained': widgets.RadioSelect(renderer=RatingRadioFieldRenderer), 'cellphone': widgets.RadioSelect(renderer=RatingRadioFieldRenderer), 'best': widgets.Textarea(attrs={'rows':5, 'cols':60,}), 'worst': widgets.Textarea(attrs={'rows':5, 'cols':60,}), 'comments': widgets.Textarea(attrs={'rows':5, 'cols':60,}), } class NewReviewForm(forms.ModelForm): building = forms.ModelChoiceField(queryset=Building.objects.filter(type=Building.TYPES_LOOKUP['Dormitory']).order_by('name')) room_number = forms.CharField() def clean(self): building = self.cleaned_data.get('building') room_number = self.cleaned_data.get('room_number') try: room = Room.objects.get(floor__building=building, number=room_number) except Room.DoesNotExist: raise ValidationError("No matching room found")
class AddendumForm(NgModelFormMixin, Bootstrap3Form): scope_prefix = 'data' annotation = fields.CharField( label=_("Supplementary annotation for this Order"), required=False, widget=widgets.Textarea(attrs={'rows': 4}))
class PublisherNoteForm(forms.Form): note = forms.CharField( label=_("Note"), widget=widgets.Textarea(), required=False )
class AddItemForm(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'} ) ) key = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='键值', help_text='必填项', widget=widgets.TextInput( attrs={'class': 'form-control'} ) ) data_type = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='数据类型', help_text='必填项', widget=widgets.Select( choices=[('int', '整数'), ('float', '小数')], attrs={'class': 'form-control'} ) ) data_unit = fields.CharField( required=False, max_length=64, error_messages={ 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='数据单位', widget=widgets.Select( choices=[('', '无'), ('KB', 'KB'), ('MB', 'MB'), ('GB', 'GB'), ('%', '百分比'), ('KB/s', 'KB/s'), ('MB/s', 'MB/s'),], attrs={'class': 'form-control'} ) ) memo = fields.CharField( required=False, error_messages={ 'invalid': '格式错误', }, label='备注', widget=widgets.Textarea( attrs={'class': 'form-control'} ) ) def clean_key(self): key = self.cleaned_data.get('key') item_obj = models.Item.objects.filter(key=key).first() if item_obj: raise ValidationError(_('监控项%(key)s已存在'), code='invalid', params={'key': key}) else: return self.cleaned_data.get('key')
class Meta: model = menchanical fields = '__all__' widgets = { 'FID': Fwidgets.Input(attrs={'type': 'hidden'}), 'FMecserialID': Fwidgets.Input( attrs={ 'class': 'layui-input', 'lay-verify': 'required', 'autocomplete': 'off' }), 'FMecspec': Fwidgets.Input( attrs={ 'class': 'layui-input', 'lay-verify': 'required', 'autocomplete': 'off' }), 'FMecsource': Fwidgets.Select(attrs={'lay-verify': 'required'}), 'FOwnerOrg': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FRecordNo': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FRecorddate': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FLease': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FManufacturer': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FProducdate': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FProducNo': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FMecmanager': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FMecmanagertel': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FParameter': Fwidgets.Input(attrs={ 'class': 'layui-input', 'autocomplete': 'off' }), 'FStatus': Fwidgets.CheckboxInput(attrs={ 'lay-skin': 'switch', 'lay-text': '启用|禁用', 'disabled': 'disabled' }), 'FDesc': Fwidgets.Textarea(attrs={ 'class': 'layui-textarea', 'autocomplete': 'off', 'rows': '1' }) }
class ArticleForm(Form): title = fields.CharField( max_length=128, required=True, label='标题(必填,128个字符以内)', widget=widgets.TextInput(attrs={"class": "form-control"}), error_messages={ 'invalid': '标题长度过长', 'required': '标题不能为空' }) summary = fields.CharField(max_length=255, required=True, label="摘要(必填,文章摘要,255个字符以内)", widget=widgets.Textarea(attrs={ "class": "form-control", "rows": 3 }), error_messages={ 'invalid': '摘要长度过长', 'required': '摘要不能为空' }) content = fields.CharField(required=False, label="正文", widget=widgets.Textarea(attrs={ "class": "form-control kind-editor", "rows": 40 })) category_id = fields.ChoiceField(choices=[], required=False, label="文章分类", widget=widgets.RadioSelect(), error_messages={"invalid": "该分类不存在"}) tag_id = fields.MultipleChoiceField( choices=[], required=False, label="文章标签", widget=widgets.CheckboxSelectMultiple(), error_messages={"invalid": "该标签不存在"}) new_tag = fields.CharField( required=False, label="使用新的标签(多个关键字之间用英文“,”分隔,最多不超过10个)", widget=widgets.TextInput(attrs={"class": "form-control"}), ) webplate_id = fields.ChoiceField( choices=[], required=False, label="网站分类", widget=widgets.RadioSelect(), error_messages={"invalid": "该网站分类不存在"}, ) def __init__(self, request, *args, **kwargs): """ :param bid: bid为blog账户的id :param aid: aid为该blog下某篇文章的id,如果是添加文章aid=None, 如果是修改文章,aid不为None :param args: 其基类Form的位置参数 :param kwargs: 其基类Form的关键字参数 """ super(ArticleForm, self).__init__(*args, **kwargs) self.bid = request.logged_blog.nid self.fields[ 'webplate_id'].choices = web_models.WebPlate.objects.values_list( 'nid', 'title') self.fields[ 'category_id'].choices = web_models.Category.objects.filter( blog_id=self.bid).values_list('nid', 'title') self.fields['tag_id'].choices = web_models.Tag.objects.filter( blog_id=self.bid).values_list('nid', 'title') def clean_new_tag(self): """ new_tag是用户新增的tag,要求以逗号分隔,不能为空,检查是否和用户已有的标签tag_dic存在重复: 如果重复则不创建Tag类实例,但是将它添加到返回列表中 如果不重复,且不为空,创建Tag类实例,同时将它添加到返回列表中 :return: 返回列表,列表中的元素是需要和Article类实例创建对对多关系的。 """ data = self.cleaned_data.get("new_tag", "") new_tag_lst = data.strip().split(',') length = len(new_tag_lst) if not length: return [] elif length > 10: raise ValidationError('新增便签长度超过10个') try: new_tag_set = set([nt.strip() for nt in new_tag_lst]) tags = web_models.Tag.objects.filter(blog_id=self.bid).only( "title", 'nid') tag_dic = {tag.title: tag.nid for tag in tags} ret = [] for nt in new_tag_set: if nt in tag_dic: ret.append(tag_dic[nt]) elif nt and nt not in tag_dic: # 当标签不为空字符串,且数据库中没有该tag时,添加该tag t = web_models.Tag.objects.create(title=nt, blog_id=self.bid) ret.append(t.nid) return ret except: raise ValidationError("添加的新标签有误,请修改后重试")
def __init__(self, attrs=None): _widgets = ( widgets.Textarea(attrs={'class': "wysiwyg-textarea"}), widgets.Textarea(attrs={'class': "wysiwyg-annotations"}), ) super(AnnotatedHTMLWidget, self).__init__(_widgets, attrs=attrs)
class CreateOrderForm(forms.Form): name = forms.CharField(label="商品名称", min_length=1, max_length=150, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "商品名称" }), error_messages={ "required": "商品名称不能为空", "min_length": "商品名称不能小于1个字符", "max_length": "商品名称不能超过150个字符" }) kind = forms.CharField(label="商品种类", widget=widgets.Select( choices=[("抗体", "抗体"), ("小分子", "小分子"), ("消耗品", "消耗品"), ("培养液", "培养液"), ("测序", "测序"), ("其他", "其他")], attrs={"class": "form-control"}), error_messages={ "required": "商品名称不能为空", "min_length": "商品名称不能小于1个字符", "max_length": "商品名称不能超过150个字符" }) company = forms.CharField(label="公司名称", min_length=1, max_length=150, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "公司名称" }), error_messages={ "required": "公司名称不能为空", "min_length": "公司名称不能小于1个字符", "max_length": "公司名称不能超过150个字符" }) unit_price = forms.DecimalField( label="商品单价", min_value=0, max_digits=10, decimal_places=2, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "商品单价" }), error_messages={ "required": "单价不能为空", "invalid": "请输入正确的单价格式", "min_value": "单价不能小于0", "max_digits": "单价不能超过10位数", "max_decimal_places": "仅支持两位小数" }) amount = forms.IntegerField(label="数量", max_value=999, min_value=1, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "商品数量" }), error_messages={ "required": "单价不能为空", "invalid": "请输入整数数量", "min_value": "商品数量不能小于1个", "max_value": "商品数量不能大于999个" }) payment = forms.DecimalField( label="订单金额", min_value=0, max_digits=10, decimal_places=2, widget=widgets.TextInput(attrs={ "class": "form-control", "placeholder": "订单金额", "readonly": '' }), error_messages={ "required": "金额不能为空", "invalid": "请输入正确的金额格式", "min_value": "金额不能小于0", "max_digits": "金额不能超过10位数", "max_decimal_places": "仅支持两位小数" }) uinfo = forms.CharField( label="备注", max_length=300, min_length=1, required=False, widget=widgets.Textarea(attrs={ "class": "form-control", "placeholder": "用户备注信息", "rows": 3 }), error_messages={ "min_length": "备注信息不能小于0个字符", "max_length": "备注信息不能大于300个字符" })
class Meta: model = FaqAnswer fields = ['text'] widgets = {'text': widgets.Textarea(attrs={'rows': 3})}
class TweetAdminForm(ModelForm): text = fields.CharField(widget=widgets.Textarea( attrs={'style': 'width:450px'}))
class Meta: model = Server fields = ('manage_ip', 'intranet_ip', 'user', 'ip', 'port', 'desc', 'sn', 'manufacturer', 'model', 'platform', 'version', 'cpu_count', 'cpu_physical_count', 'cpu_model', 'mac', 'serial_num', 'name', 'port_num', 'id') exclude = None #排除的字段 labels = None #提示信息 help_texts = None #帮助提示信息 widgets = None #自定义插件 error_messages = None #自定义错误信息 widgets = { "manage_ip": wid.TextInput(attrs={ 'class': 'smallinput', 'placeholder': "如:10.24.22.12" }), "intranet_ip": wid.TextInput(attrs={ 'class': 'smallinput', 'placeholder': "如:192.168.1.240" }), "user": wid.Select(choices=common.VERSION_STATUS_VALUE), "ip": wid.TextInput(attrs={ 'class': 'smallinput', 'placeholder': "如:23.24.22.12" }), "port": wid.TextInput(attrs={'class': 'smallinput'}), "desc": wid.Textarea(attrs={ 'class': 'smallinput', 'placeholder': "如:本地机房服务器,在2楼xxx办公室" }), "sn": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "manufacturer": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "model": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "platform": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "version": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "cpu_count": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "cpu_physical_count": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "cpu_model": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "mac": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "serial_num": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "name": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "port_num": wid.TextInput(attrs={ 'class': 'smallinput', 'readonly': "readonly" }), "id": wid.HiddenInput(), }
class Meta: model = KubeConfig fields = ('kube_name', 'kube_version', 'deploy_mode', 'deploy_node', 'ntp_enabled', 'ssh_addkey', 'node_port_range', 'master_ip', 'kube_api_server', 'cluster_network', 'service_cidr', 'cluster_cidr', 'cluster_k8s_svc_ip', 'cluster_dns_svc_ip', 'cluster_dns_domain', 'basic_auth_user', 'basic_auth_pass', 'bin_dir', 'ca_dir', 'base_dir', 'kube_desc', 'id', 'deploy', 'deploy_status') exclude = None #排除的字段 labels = None #提示信息 help_texts = None #帮助提示信息 widgets = None #自定义插件 error_messages = None #自定义错误信息 widgets = { "kube_name": wid.Select(choices=common.K8S_FLAG, attrs={'style': 'margin: 0px;height:30px'}), "kube_version": wid.Select(choices=common.K8S_VERSION, attrs={'style': 'margin: 0px;height:30px'}), "deploy_mode": wid.Select(choices=common.K8S_DEPLOY_MODE, attrs={'style': 'margin: 0px;height:30px'}), "deploy_node": wid.TextInput(attrs={ 'class': 'smallinput', 'value': "192.168.150.181" }), "ntp_enabled": wid.Select(choices=common.COMMON_STATUS, attrs={'style': 'margin: 0px;height:30px'}), "ssh_addkey": wid.Select(choices=common.COMMON_STATUS, attrs={'style': 'margin: 0px;height:30px'}), "node_port_range": wid.TextInput( attrs={ 'class': 'smallinput', 'value': '20000-40000', 'readonly': 'readonly' }), "master_ip": wid.TextInput(attrs={ 'class': 'smallinput', 'placeholder': "如:192.168.150.187" }), "kube_api_server": wid.TextInput(attrs={ 'class': 'smallinput', 'value': 'https://$loadblance_vip:8443' }), "cluster_network": wid.Select(choices=common.K8S_CLUSTER_NETWORK, attrs={'style': 'margin: 0px;height:30px'}), "service_cidr": wid.TextInput(attrs={ 'class': 'smallinput', 'value': "10.68.0.0/16" }), "cluster_cidr": wid.TextInput(attrs={ 'class': 'smallinput', 'value': "172.20.0.0/16" }), "cluster_k8s_svc_ip": wid.TextInput(attrs={ 'class': 'smallinput', 'value': "10.68.0.1" }), "cluster_dns_svc_ip": wid.TextInput(attrs={ 'class': 'smallinput', 'value': "10.68.0.2" }), "cluster_dns_domain": wid.TextInput(attrs={ 'class': 'smallinput', 'value': "cluster.local." }), "basic_auth_user": wid.TextInput(attrs={ 'class': 'smallinput', 'placeholder': '如:admin' }), "basic_auth_pass": wid.TextInput(attrs={ 'class': 'smallinput', 'placeholder': '如:admin123456' }), "bin_dir": wid.TextInput( attrs={ 'class': 'smallinput', 'readonly': 'readonly', 'value': '/opt/kube/bin' }), "ca_dir": wid.TextInput( attrs={ 'class': 'smallinput', 'readonly': 'readonly', 'value': '/etc/kubernetes/ssl' }), "base_dir": wid.TextInput( attrs={ 'class': 'smallinput', 'readonly': 'readonly', 'value': '/etc/ansible' }), "kube_desc": wid.Textarea(attrs={'class': 'smallinput'}), "id": wid.HiddenInput(), "deploy": wid.HiddenInput(), "deploy_status": wid.HiddenInput(), }
class PactPatientForm(Form): """ DocumentForm """ pactid = forms.CharField(label="PACT ID", required=True) first_name = forms.CharField(label="First Name", required=True) middle_name = forms.CharField(label="Middle Name", required=False) last_name = forms.CharField(label="Last Name", required=True) gender = forms.ChoiceField(label="Sex", choices=GENDER_CHOICES) #source: http://stackoverflow.com/questions/1513502/django-how-to-format-a-datefields-date-representation dob = forms.DateField(required=False, label='DOB (m/d/y)', input_formats=['%m/%d/%Y'], widget=forms.DateInput(format='%m/%d/%Y', attrs={'class': 'jqui-dtpk'})) race = forms.ChoiceField(choices=PACT_RACE_CHOICES) preferred_language = forms.ChoiceField(choices=PACT_LANGUAGE_CHOICES) mass_health_expiration = forms.DateField( label="Mass Health expiration date (m/d/y)", input_formats=['%m/%d/%Y', ''], widget=forms.DateInput(format='%m/%d/%Y'), required=False) ssn = forms.CharField(label="Social Security Number", required=False) hp = forms.ChoiceField(label="Primary health promoter", choices=()) hp_status = forms.ChoiceField(label="HP Status", choices=PACT_HP_CHOICES, required=False) dot_status = forms.ChoiceField(label="DOT Status", choices=PACT_DOT_CHOICES, required=False) artregimen = forms.ChoiceField(choices=PACT_REGIMEN_CHOICES, required=False) nonartregimen = forms.ChoiceField(choices=PACT_REGIMEN_CHOICES, required=False) hiv_care_clinic = forms.ChoiceField(choices=PACT_HIV_CLINIC_CHOICES) patient_notes = forms.CharField(widget=widgets.Textarea(attrs={ 'cols': 80, 'rows': 5 }), required=False) def __init__(self, request, casedoc, *args, **kwargs): super(PactPatientForm, self).__init__(*args, **kwargs) self.casedoc = casedoc self.fields['hp'].choices = get_hp_choices() self.case_es = ReportCaseES(request.domain) for name, field in self.fields.items(): if name == CASE_ART_REGIMEN_PROP: #these really should be a widget of some type #dereference the artregimen, dot_a_one...etc to become the comma separated regimen string for the form art_regimen_initial = self.casedoc.art_regimen_label_string() casedoc_value = art_regimen_initial elif name == CASE_NONART_REGIMEN_PROP: nonart_regimen_initial = self.casedoc.nonart_regimen_label_string( ) casedoc_value = nonart_regimen_initial else: casedoc_value = getattr(self.casedoc, name, '') field.initial = casedoc_value @property def clean_changed_data(self): #to be called after validation ret = {} for name, value in self.cleaned_data.items(): #to verify that the regimens changed calculate the dict of the freq+label ids. if name == CASE_ART_REGIMEN_PROP: art_props = regimen_dict_from_choice(DOT_ART, value) if art_props != self.casedoc.art_properties(): ret.update(art_props) elif name == CASE_NONART_REGIMEN_PROP: nonart_props = regimen_dict_from_choice(DOT_NONART, value) if nonart_props != self.casedoc.nonart_properties(): ret.update(nonart_props) else: if getattr(self.casedoc, name, '') != value: ret[name] = value # hack, if any of the names, change remake the name and initials name_changed = False if 'first_name' in list(ret.keys()): name_changed = True first_name = ret['first_name'] else: first_name = self.casedoc.first_name if 'last_name' in list(ret.keys()): name_changed = True last_name = ret['last_name'] else: last_name = self.casedoc.last_name if name_changed: ret['name'] = '%s %s' % (first_name, last_name) ret['initials'] = '%s%s' % ( first_name[0] if len(first_name) > 1 else '', last_name[0] if len(last_name) > 0 else '') return ret def clean_dob(self): if self.cleaned_data['dob'] is not None: return json_format_date(self.cleaned_data['dob']) else: return None def clean_mass_health_expiration(self): if self.cleaned_data['mass_health_expiration'] is not None: return json_format_date( self.cleaned_data['mass_health_expiration']) else: return None
class ETicketSolutionForm(Form): content = fields.CharField(widget=widgets.Textarea( attrs={'class': 'form-control'}))
def score( request, ques_id, cls_id, ): stu_id = request.session.get("id") #从session中取出当前登录用户的ID if not stu_id: return redirect("/student_login/") #判断当前登录的用户是否是要答卷的班级的学生 stu_obj = models.Student.objects.filter(id=stu_id, cls_id=cls_id).count() if not stu_obj: return HttpResponse("对不起,您不是本次问卷调查对象") #判断是否已经提交过问卷答案 has_join = models.Answer.objects.filter(user_id=stu_id, question__questionnaire_id=ques_id) if has_join: return HttpResponse("对不起,您已经参与过本次问卷,不可重复参与") #展示当前问卷下的所有问题 #获取当前问卷的所有问题 question_list = models.Question.objects.filter(questionnaire_id=ques_id) field_dict = {} for que in question_list: if que.ct == 1: field_dict["val_%s" % que.id] = fields.ChoiceField( label=que.caption, error_messages={"required": "必填"}, widget=widgets.RadioSelect, choices=[(i, i) for i in range(1, 11)]) elif que.ct == 2: field_dict["option_id_%s" % que.id] = fields.ChoiceField( label=que.caption, error_messages={"required": "必填"}, widget=widgets.RadioSelect, ##这里数据表option中的score是不需要给用户看到的 choices=models.Option.objects.filter( question_id=que.id).values_list("id", "name")) else: field_dict["content_%s" % que.id] = fields.CharField( label=que.caption, error_messages={"required": "必填"}, widget=widgets.Textarea(attrs={ "class": "form-control", "rows": "2", "cols": "60" }), validators=[ func, ] #这里可以写正则,也可以自定义函数放在这里 ) myForm = type("myTestForm", (Form, ), field_dict) #动态生成类,参数分别是类名,继承的对象,字段 if request.method == "GET": form = myForm() return render(request, "score.html", { "question_list": question_list, "form": form }) else: form = myForm(request.POST) if form.is_valid(): obj_list = [] for key, v in form.cleaned_data.items(): print(key, v) key, qid = key.rsplit("_", 1) #从右边切,切一次 answer_dict = {"user_id": stu_id, "question_id": qid, key: v} print(answer_dict) obj_list.append(models.Answer(**answer_dict)) models.Answer.objects.bulk_create(obj_list) #批量插入 return HttpResponse("感谢您的参与") return render(request, "score.html", { "question_list": question_list, "form": form })
class Meta: widgets = {'message': widgets.Textarea()}
class MOTDForm(happyforms.Form): motd = forms.CharField(widget=widgets.Textarea())
class Meta: model = Host exclude = ['create_date', 'update_date'] widgets = { 'ip_managemant': frwidgets.Input(attrs={ 'class': 'form-control', 'placeholder': '请输入IP地址...' }), 'ip_other1': frwidgets.Input(attrs={ 'class': 'form-control', 'placeholder': '请输入IP地址...' }), 'ip_other2': frwidgets.Input(attrs={ 'class': 'form-control', 'placeholder': '请输入IP地址...' }), 'os_type': frwidgets.Select(attrs={'class': 'custom-select d-block w-100'}), 'os_release': frwidgets.Input(attrs={'class': 'form-control'}), 'cpu_physics_count': frwidgets.Input(attrs={'class': 'form-control'}), 'cpu_core_count': frwidgets.Input(attrs={'class': 'form-control'}), 'cpu_logic_count': frwidgets.Input(attrs={'class': 'form-control'}), 'mem_capacity': frwidgets.Input(attrs={'class': 'form-control'}), 'disk_capacity': frwidgets.Input(attrs={'class': 'form-control'}), 'raid_type': frwidgets.Select(attrs={'class': 'custom-select d-block w-100'}), 'mac_address': frwidgets.Input(attrs={'class': 'form-control'}), 'name': frwidgets.Input(attrs={'class': 'form-control'}), 'sn': frwidgets.Input(attrs={'class': 'form-control'}), 'asset_type': frwidgets.Select(attrs={'class': 'custom-select d-block w-100'}), 'model': frwidgets.Input(attrs={'class': 'form-control'}), 'manufactory': frwidgets.Select(attrs={'class': 'form-control'}), 'supplier': frwidgets.Select(attrs={'class': 'form-control'}), 'trade_date': frwidgets.DateInput(attrs={ 'class': 'form-control', 'placeholder': 'YYYY-MM-DD' }), 'expire_date': frwidgets.DateInput(attrs={ 'class': 'form-control', 'placeholder': 'YYYY-MM-DD' }), 'idc': frwidgets.Select(attrs={'class': 'form-control'}), 'cabinet': frwidgets.Input(attrs={'class': 'form-control'}), 'cabinet_uid': frwidgets.Input(attrs={'class': 'form-control'}), 'memo': frwidgets.Textarea(attrs={'class': 'form-control'}), }
class ServiceRecordForm(forms.Form): description = forms.CharField(label = 'Relatório', widget = widgets.Textarea())
class AddendumForm(NgModelFormMixin, Bootstrap3Form): annotation = fields.CharField( label="", widget=widgets.Textarea(attrs={'rows': 2}), )
class OccurrenceCallEditionForm(forms.Form): description = forms.CharField(label = 'Descrição', widget = widgets.Textarea()) status = forms.ChoiceField(choices = (('-----', '-----'), ('Aberto', 'Aberto'), ('Em Andamento', 'Em Andamento'), ('Fechado', 'Fechado')), label = 'Status do Chamado')
class Meta: model = Event fields = [ "event_date", "event_time", "event_place", "duration", "nb_max", "description", # Additional fields # "participation", # "diffusion", ] widgets = { "duration": widgets.NumberInput(attrs={ "class": "uk-input", "placeholder": "cinq minutes, c'est pas mal" }), "nb_max": widgets.NumberInput(attrs={ "class": "uk-input", "placeholder": "conseil : entre six et huit" }), "event_date": SelectDateWidget(months=months, attrs={"class": "uk-select event-date-select"}), "event_time": SelectTimeWidget(twelve_hr=True, minute_step=5, attrs={"class": "uk-input event-time-select"}), "event_place": widgets.TextInput( attrs={ "class": "uk-input", "placeholder": "une place publique, une agora, un charmant salon" }), "description": widgets.Textarea(attrs={"class": "uk-textarea"}), "participation": widgets.Select(choices=( (1, "Quiconque peut participer"), (2, "Sur invitation du créateur seulement"), (3, "Sur invitation d'un participant"), )), "diffusion": widgets.Select(choices=( (1, "Quiconque peut accéder aux discours"), (2, "Seuls les participants peuvent accéder au discours"), (3, "Seul l'auteur peut accéder à son discours"), )) } labels = { "duration": "Quelle durée de discours (en minutes) ?", "nb_max": "Combien de locuteurs au maximum ?", "event_date": "Quand ça ?", "event_time": "À quelle heure ?", "event_place": "Où donc ?", "description": "Quelque chose à ajouter ?", "participation": "Participation", "diffusion": "Diffusion", }
class PersonneTravelForm(FormForceLocalizedDateFields): class Meta: model = PersonneTravel exclude = ( 'personne', 'travel', 'date_start', 'date_end', 'comments', 'date_v_debut', 'date_v_fin', 'ignore_start_dd', 'ignore_start_mm', 'ignore_end_dd', 'ignore_end_mm', 'photo1', 'photo2', 'photo3', ) e = { 'required': _(u'This field is required'), 'invalid': _(u'This field contains invalid data') } a = _(u'Town / Country / Place:') travel = forms.CharField( # (!) laisser required=False, je le gère plus loin s'il est vide : label=a, max_length=100, required=False, widget=GoogleMapsWidget( attrs={ 'title': a, 'size': 100, 'type': 'text', 'rowstart': True, 'rowspan': 12, 'rowend': True, 'placeholder': _(u'town / country / place'), 'class': 'form-control' }), error_messages=e) a = _(u'Start:') date_start = FormFieldDatePartial( label=a, localize=True, required=False, widget=DateSelectorWidget( attrs={ 'title': a, 'rowstart': True, 'rowspan': 6, 'style': "display: inline-block; width: auto", 'class': 'form-control' })) a = _(u'End:') date_end = FormFieldDatePartial( label=a, localize=True, required=False, widget=DateSelectorWidget( attrs={ 'title': a, 'rowspan': 6, 'rowend': True, 'style': "display: inline-block; width: auto", 'class': 'form-control' })) a = _(u'Add a comment:') comments = forms.CharField(label=a, localize=True, required=False, widget=widgets.Textarea( attrs={ 'title': a, 'rows': 5, 'cols': 40, 'style': 'resize: vertical', 'rowstart': True, 'rowspan': 6, 'rowend': True, 'class': 'form-control' })) is_past = forms.BooleanField(required=False, widget=widgets.HiddenInput()) def __init__(self, *args, **kwargs): super(PersonneTravelForm, self).__init__(*args, **kwargs) kw = kwargs.get('initial') # I've made a CustomImageField to be able to pass custom parameters # 'picture_attributes' where I put infos on the image so I can easily # display the image in the template through "field.picture_attributes": def local_creer_custom_image_field(idx): img = None if kw: photo = kw.get('field_photo_{}'.format(idx)) if photo: img = str(photo.url()) if not img: # url vide = image d'une photo vide img = PictureURL.get_url() l_a = _(u'Picture {}:').format(idx) return CustomImageField( label=l_a, allow_empty_file=True, required=False, help_text=None if idx > 1 else _( u"<span class=\"suggestion\">" u"Want to upload photos of your different experiences and " u"inspire future travellers?</span>"), picture_attributes={ 'width': 'auto', 'height': 100, 'style': 'margin:10px; ', 'url': img }, widget=forms.FileInput( attrs={ 'title': l_a, 'rowstart': True, 'rowspan': 12, 'rowend': True, 'placeholder': _(u'picture {}').format(idx), 'class': 'form-control travel-image', 'accept': "image/*", }), error_messages=self.e) field_photo_1 = local_creer_custom_image_field(1) field_photo_2 = local_creer_custom_image_field(2) field_photo_3 = local_creer_custom_image_field(3) # -------------------------------------------------------------------- # Problème : self.fields est de type OrderedDict(), qui se base sur # l'ordre d'ajout des éléments. Alors si on veut un autre # ordre, pas d'autre choix que de reconstruire # le dictionnaire en y appliquant l'ordre qu'on veut : new_fields = OrderedDict([ ('travel', self.fields['travel']), ('date_start', self.fields['date_start']), ('date_end', self.fields['date_end']), ('comments', self.fields['comments']), ('field_photo_1', field_photo_1), ('field_photo_2', field_photo_2), ('field_photo_3', field_photo_3), ]) # Des fois, je construis la forme "manuellement" en lui envoyant # directement les champs dans un dict() PersonneTravelForm({ info }) # Tous les champs passés sont ceux attendus, mais EN PLUS # j'y ajoute le pk comme ça dans mon code, si je vois que le # pk est présent, c'est une édition de la forme et je fais un update if len(args): if 'pk' in args[0]: new_fields['pk'] = forms.IntegerField( widget=widgets.HiddenInput()) elif kw: if kw.get('pk'): new_fields['pk'] = forms.IntegerField( widget=widgets.HiddenInput()) elif kwargs.get('data'): pk = kwargs.get('data').get('pk') if pk: # pk revenu dans le post = cf long commentaire au dessus new_fields['pk'] = forms.IntegerField( widget=widgets.HiddenInput()) for kw, v in self.fields.items(): if not new_fields.get(kw): # (!) que s'ils n'y sont pas new_fields[kw] = v self.fields = new_fields def handle_uploaded_photos(self, field): original, final = self.files.get(field), None if original: try: final = UploadedPictureHandler().encode_filename( original, 'travels/') return Photo.objects.create(fichier_origine=original, image=final) except IOError: self.errors[field] = ErrorList([_(u"Unknown type of image")]) return None def clean_field_photo_1(self): return self.handle_uploaded_photos('field_photo_1') def clean_field_photo_2(self): return self.handle_uploaded_photos('field_photo_2') def clean_field_photo_3(self): return self.handle_uploaded_photos('field_photo_3') def clean_date_start(self): # Je ne sais pas comment remonter l'erreur via mon widget custom # car l'erreur est levée au niveau d'un DatePartial, je l'ai donc # gardée dans un tableau "errors" que je vérifie ici : if len(self.fields['date_start'].widget.errors): raise ValidationError(_( self.fields['date_start'].widget.errors[0])) return str(self.fields['date_start'].widget.date_partial) def clean_travel(self): travel = self.cleaned_data['travel'] if travel == '': return None langue = Langue.objects.get(locale__exact=translation.get_language()) locale = langue.locale try: retour = TagGoogleMapsTraduit.objects.get( langue__locale__exact=locale, formatted_address__iexact=travel) except MultipleObjectsReturned: # Garder le plus long () retour = None for a in TagGoogleMapsTraduit.objects.filter( langue__locale__exact=locale, formatted_address__iexact=travel): if retour: # Si des min et des maj c'est sûrement un retour google if any(x.isupper() for x in str(a)) and \ any(x.islower() for x in str(a)): # Si il est le plus long if len(retour.formatted_address) < \ len(a.formatted_address): # Min/maj + plus long -> on le garde retour = a else: retour = a except TagGoogleMapsTraduit.DoesNotExist: try: retour = TagGoogleMapsTraduit.make_cache_via_google_maps( text=travel, locale=locale) except GoogleException as e: raise ValidationError(e.message) return retour def clean_pk(self): try: return int(self.cleaned_data['pk']) except ValueError: return None def clean(self): # print(self.cleaned_data) # Arrivé ici c'est après tous les appels à clean_XXX où XXX = champ du # formulaire. Ici on est censé faire une vérification "globale", c'est # à dire une vérification qui ne concerne pas un champ en particulier. return super(PersonneTravelForm, self).clean()
class EditItemForm(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'} ) ) key = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='键值', help_text='必填项', widget=widgets.TextInput( attrs={'class': 'form-control'} ) ) data_type = fields.CharField( max_length=64, error_messages={ 'required': '不能为空', 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='数据类型', help_text='必填项', widget=widgets.Select( choices=[('int', '整数'), ('float', '小数')], attrs={'class': 'form-control'} ) ) data_unit = fields.CharField( required=False, max_length=64, error_messages={ 'invalid': '格式错误', 'max_length': '最大长度不能大于64位' }, label='数据单位', widget=widgets.Select( choices=[('', '无'), ('KB', 'KB'), ('MB', 'MB'), ('GB', 'GB'), ('%', '百分比'), ('KB/s', 'KB/s'), ('MB/s', 'MB/s'), ], 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(EditItemForm, self).__init__(*args, **kwargs) self.iid = self.initial['iid'] item_obj = models.Item.objects.filter(id=self.iid).first() self.fields['name'].initial = item_obj.name self.fields['key'].initial = item_obj.key self.fields['data_type'].initial = item_obj.data_type self.fields['data_unit'].initial = item_obj.data_unit self.fields['memo'].initial = item_obj.memo def clean_key(self): key = self.cleaned_data.get('key') count = models.Item.objects.exclude(id=self.iid).filter(key=key).count() if count: raise ValidationError(_('监控项%(key)s已存在'), code='invalid', params={'key': key}) else: return self.cleaned_data.get('key')
def investigation(request, naire_id): ''' 开始问卷调查 ''' field_dict = {} request.session["naire_id"] = naire_id print(naire_id) question_list = Question.objects.filter(questionnaire_id=naire_id) for question in question_list: if question.tp == 1: field_dict["val_%s" % question.id] = fields.ChoiceField( label=question.caption, error_messages={"required": "请选择!"}, choices=[(x, x) for x in range(1, 11)], widget=widgets.RadioSelect) elif question.tp == 2: field_dict["option_id_%s" % question.id] = fields.ChoiceField( label=question.caption, error_messages={"required": "请选择!"}, choices=question.option_set.all().values_list("id", "name"), widget=widgets.RadioSelect) elif question.tp == 3: field_dict["content_%s" % question.id] = fields.CharField( label=question.caption, min_length=15, error_messages={ "required": "不能为空!", "min_length": "不能少于15个字" }, widget=widgets.Textarea( attrs={ "cols": "40", "rows": "3", "class": "form-control Textarea", "placeholder": "请输入建议!,最少15个字" })) # type创建类对象 TestForm = type('TestForm', (Form, ), field_dict) if request.method == 'GET': print(field_dict) form = TestForm() return render(request, 'investigation.html', {"form": form}) else: # answer_list = json.loads(request.body) # print(answer_list) # form = TestForm(answer_list) data = request.POST print(data) form = TestForm(data) if form.is_valid(): print("success") for key, val in data.items(): aa = {} if key == "csrfmiddlewaretoken": continue ans_k, que_id = key.rsplit("_", 1) aa[ans_k] = val print("aa", aa) Answer.objects.create(stu_id=1, question_id=que_id, questionnaire_id=naire_id, **aa) return HttpResponse("ok") return render(request, 'investigation.html', {"form": form})
class MOTDForm(forms.Form): motd = forms.CharField(required=True, widget=widgets.Textarea())
def get_form(self, **kwargs): form = super(RobotUpdateView, self).get_form(**kwargs) form.fields['videoLink'].widget = widgets.Textarea() form.fields['notes'].widget = widgets.Textarea() return form
class SubscribeForm(Bootstrap3Form): use_required_attribute = False CONTINENT_CHOICES = [('am', 'America'), ('eu', 'Europe'), ('as', 'Asia'), ('af', 'Africa'), ('au', 'Australia'), ('oc', 'Oceania'), ('an', 'Antartica')] TRAVELLING_BY = [('foot', 'Foot'), ('bike', 'Bike'), ('mc', 'Motorcycle'), ('car', 'Car'), ('public', 'Public Transportation'), ('train', 'Train'), ('air', 'Airplane')] NOTIFY_BY = [('email', 'EMail'), ('phone', 'Phone'), ('sms', 'SMS'), ('postal', 'Postcard')] first_name = fields.CharField(label='First name', min_length=3, max_length=20) last_name = fields.RegexField( r'^[A-Z][a-z -]?', label='Last name', error_messages={'invalid': 'Last names shall start in upper case'}) sex = fields.ChoiceField( choices=(('m', 'Male'), ('f', 'Female')), widget=widgets.RadioSelect, error_messages={'invalid_choice': 'Please select your sex'}) email = fields.EmailField(label='E-Mail', required=True, help_text='Please enter a valid email address') subscribe = fields.BooleanField(label='Subscribe Newsletter', initial=False, required=False) phone = fields.RegexField( r'^\+?[0-9 .-]{4,25}$', label='Phone number', error_messages={ 'invalid': 'Phone number have 4-25 digits and may start with +' }) birth_date = fields.DateField( label='Date of birth', widget=widgets.DateInput( attrs={'validate-date': '^(\d{4})-(\d{1,2})-(\d{1,2})$'}), help_text='Allowed date format: yyyy-mm-dd') continent = fields.ChoiceField( label='Living on continent', choices=CONTINENT_CHOICES, error_messages={'invalid_choice': 'Please select your continent'}) weight = fields.IntegerField( label='Weight in kg', min_value=42, max_value=95, error_messages={'min_value': 'You are too lightweight'}) height = fields.FloatField( label='Height in meters', min_value=1.48, max_value=1.95, step=0.05, error_messages={'max_value': 'You are too tall'}) traveling = fields.MultipleChoiceField( label='Traveling by', choices=TRAVELLING_BY, help_text='Choose one or more carriers', required=True) notifyme = fields.MultipleChoiceField( label='Notify by', choices=NOTIFY_BY, widget=widgets.CheckboxSelectMultiple, help_text='Must choose at least one type of notification') annotation = fields.CharField(label='Annotation', required=True, widget=widgets.Textarea(attrs={ 'cols': '80', 'rows': '3' })) agree = fields.BooleanField(label='Agree with our terms and conditions', initial=False, required=True) password = fields.CharField(label='Password', widget=widgets.PasswordInput, validators=[validate_password], help_text='The password is "secret"') confirmation_key = fields.CharField(max_length=40, required=True, widget=widgets.HiddenInput(), initial='hidden value')
class UserInfoForm(forms.Form): """ UserInfoForm用于1、生成后台管理中,用户信息填写的input表单代码 2、帮助验证用户输入的信息是否合乎规范 username:用户名 email:用户邮箱 user_nickname:用户昵称 blog_title:博客标题 上述四个字段在用户信息管理页面中都可输入为空,输入为空点击保存表示对用户信息不予修改 """ username = fields.CharField( max_length=64, required=False, widget=widgets.TextInput(attrs={"class":"form-control","placeholder":"请输入用户名"}), error_messages={ "max_length":"用户名太长了", }) email = fields.EmailField( required=False, widget=widgets.TextInput(attrs={"class":"form-control","placeholder":"请输入邮箱"}), error_messages={ "invalid":"邮箱格式不正确" }) user_nickname = fields.CharField( max_length=32, required=False, widget=widgets.TextInput(attrs={"class":"form-control","placeholder":"请输入昵称"}), error_messages={ "max_length":"昵称过长", }) blog_title = fields.CharField( max_length=128, required=False, widget=widgets.Textarea(attrs={"class":"form-control","style":"height: 120px"}), error_messages={ "max_length": "博客标题太长", }) def __init__(self,username,*args,**kwargs): self.username = username super(UserInfoForm, self).__init__(*args,**kwargs) print(self.fields["username"]) self.fields["username"].widget = widgets.TextInput(attrs={"class":"form-control","placeholder":"%s"%username}) user_obj= models.UserTable.objects.filter(username=username).first() email = user_obj.email nick_name = user_obj.user_nickname self.fields["email"].widget = widgets.TextInput(attrs={"class":"form-control","placeholder":"%s"%email}) self.fields["user_nickname"].widget = widgets.TextInput(attrs={"class":"form-control","placeholder":"%s"%nick_name}) def clean_username(self): """ 对用户名字段进行再次验证, 1、输入的是原来自己的用户名,返回该用户名 2、输入的是库中没有存在的用户名,返回该用户名 3、输入的是已经存在,别人使用的用户名,抛出异常‘用户名已经存在’ :return: """ user = self.cleaned_data.get("username") if user == self.username: return self.cleaned_data["username"] elif user: if models.UserTable.objects.filter(username=user).count(): raise ValidationError("用户名已经存在") else: return self.cleaned_data["username"]