class TestForm(forms.Form): n1 = fields.CharField(widget=widgets.PasswordInput()) n2 = fields.CharField(widget=widgets.Textarea()) n3 = fields.CharField(widget=widgets.Select(choices=[ (1, "上海"), (2, "北京"), (3, "广州"), ])) n4 = fields.ChoiceField(choices=[(1, "上海"), (2, "北京"), (3, "广州")], widget=widgets.SelectMultiple()) n5 = fields.IntegerField(widget=widgets.RadioSelect(choices=[ (1, '上海'), (2, '北京'), ])) n6 = fields.CharField(widget=widgets.CheckboxInput()) n7 = fields.ChoiceField(choices=[ (1, '上海'), (2, '北京'), ], widget=widgets.CheckboxSelectMultiple()) n8 = fields.FileField()
def inputScore(self,request,cr_id): if request.method=='GET': studyRecord_list=models.StudyRecord.objects.filter(course_record_id=cr_id) data=[] for studyRecord in studyRecord_list: #动态生成form SRForm=type('SRForm',(Form,),{ 'score_%s'%studyRecord.id : fields.ChoiceField(models.StudyRecord.score_choices), 'homework_note_%s'%studyRecord.id :fields.ChoiceField(widget=widgets.Textarea(attrs={"style":'width:395px;height:45px'})) }) data.append({"studyRecord":studyRecord,"form":SRForm(initial={'score_%s'%studyRecord.id:studyRecord.score,'homework_note_%s'%studyRecord.id:studyRecord.homework_note})}) return render(request,'inputScore.html',{'data':data}) else: data=request.POST print(data) for k,v in data.items(): if k=='csrfmiddlewaretoken': continue name,studyRecord_id=k.rsplit('_',1) data_dic={} if studyRecord_id in data_dic: data_dic[studyRecord_id][name]=v else: data_dic[studyRecord_id]={name:v} for id,dic in data_dic.items(): models.StudyRecord.objects.filter(id=id).update(**dic) return redirect(self.get_list_url())
class SearchPagesFormBase(forms.Form): state = fields.ChoiceField(choices=[]) date1 = fields.ChoiceField(choices=[]) date2 = fields.ChoiceField(choices=[]) proxtext = fields.CharField() issue_date = fields.BooleanField() def __init__(self, *args, **kwargs): super(SearchPagesFormBase, self).__init__(*args, **kwargs) self.titles, self.states = _titles_states() fulltextStartYear, fulltextEndYear = _fulltext_range() self.years = [(year, year) for year in range(fulltextStartYear, fulltextEndYear + 1) ] self.fulltextStartYear = fulltextStartYear self.fulltextEndYear = fulltextEndYear self.fields["state"].choices = self.states self.fields["date1"].choices = self.years self.fields["date1"].initial = fulltextStartYear self.fields["date2"].choices = self.years self.fields["date2"].initial = fulltextEndYear
class SearchPagesForm(forms.Form): # state = fields.ChoiceField(choices=[]) date1 = fields.ChoiceField(choices=[]) date2 = fields.ChoiceField(choices=[]) proxtext = fields.CharField() sequence = fields.BooleanField() issue_date = fields.BooleanField() def __init__(self, *args, **kwargs): super(SearchPagesForm, self).__init__(*args, **kwargs) # self.titles, self.states = _titles_states() # added by MK self.titles = _titles_options() self.cities = _cities_options() self.counties = _counties_options() self.types = _types_options() self.regions = _regions_options() fulltextStartYear, fulltextEndYear = _fulltext_range() self.years = [(year, year) for year in range(fulltextStartYear, fulltextEndYear + 1) ] self.fulltextStartYear = fulltextStartYear self.fulltextEndYear = fulltextEndYear # self.fields["state"].choices = self.states self.fields["date1"].choices = self.years self.fields["date1"].initial = fulltextStartYear self.fields["date2"].choices = self.years self.fields["date2"].initial = fulltextEndYear self.fields["sequence"].widget.attrs['value'] = 1
class AdvSearchPagesForm(SearchPagesForm): lccn = fields.MultipleChoiceField(choices=[]) state = fields.MultipleChoiceField(choices=[]) date1 = fields.CharField() date2 = fields.CharField() sequence = fields.CharField() ortext = fields.CharField() andtext = fields.CharField() phrasetext = fields.CharField() proxtext = fields.CharField() proxdistance = fields.ChoiceField(choices=PROX_CHOICES) language = fields.ChoiceField() def __init__(self, *args, **kwargs): super(AdvSearchPagesForm, self).__init__(*args, **kwargs) self.date = self.data.get('date1', '') self.fields["lccn"].widget.attrs = {'id': 'id_lccns', 'size': '8'} self.fields["lccn"].choices = self.titles self.fields["state"].widget.attrs = {'id': 'id_states', 'size': '8'} self.fields["date1"].widget.attrs = {"id": "id_date_from", "max_length": 10} self.fields["date1"].initial = "" self.fields["date2"].widget.attrs = {"id": "id_date_to", "max_length": 10} self.fields["date2"].initial = "" self.fields["sequence"].widget.attrs = {"id": "id_char_sequence", "size": "3"} self.fields["proxtext"].widget.attrs["id"] = "id_proxtext_adv" lang_choices = [("", "All"), ] lang_choices.extend((l, models.Language.objects.get(code=l).name) for l in settings.SOLR_LANGUAGES) self.fields["language"].choices = lang_choices
class SearchForm(forms.Form): host = fields.ChoiceField( choices=((None,'全部'),(1,'kvm1'),(2,'kvm2'),(3,'kvm3'),(4,'kvm4'),(5,'kvm5'),(9,'其它')), label='主机', label_suffix=':', required=False, widget=fields.Select( attrs={'class': 'form-control d-inline col-1', 'style': 'min-width: 100px;'}) #validators=[RegexValidator(r'[1-5]', '...')] ) name = fields.CharField(required=False, label='名称', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control d-inline col-2 font-weight-light', 'placeholder': '虚拟机名称', 'style': 'min-width: 130px;'})) ip = fields.CharField(required=False, label='IP', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control d-inline col-2 font-weight-light', 'placeholder': '虚拟机IP', 'style': 'min-width: 130px;'})) status = fields.ChoiceField( choices=((None, '全部'),(1,'运行中'),(2,'关闭'),(3,'不存在')), label='状态', label_suffix=':', required=False, widget=fields.Select( attrs={'class': 'form-control d-inline col-1', 'style': 'min-width: 100px;'}) ) description = fields.CharField(required=False, label='描述', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control d-inline col-2 font-weight-light', 'placeholder': '用途 or 备注', 'style': 'min-width: 130px;'}))
class ArticleForm(django_forms.Form): title = django_fields.CharField( error_messages={'required': ' >>错误提示:标题不能为空'}, widget=django_widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': '文章标题' }, )) summary = django_fields.CharField( error_messages={'required': ' >>错误提示:简介不能为空'}, widget=django_widgets.Textarea(attrs={ 'class': 'form-control', 'placeholder': '文章简介', 'rows': '3' })) content = django_fields.CharField( error_messages={'required': ' >>错误提示:内容不能为空'}, widget=django_widgets.Textarea(attrs={'class': 'kind-content'})) article_type_id = django_fields.IntegerField( error_messages={'required': ' >>错误提示:请选择文章类型!'}, widget=django_widgets.RadioSelect(choices=models.Article.type_choices)) category_id = django_fields.ChoiceField( error_messages={'required': ' >>错误提示:请选择文章分类'}, widget=django_widgets.RadioSelect) tag_id = django_fields.ChoiceField( error_messages={'required': ' >>错误提示:请选择文章标签'}, widget=django_widgets.RadioSelect) def __init__(self, request, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) blog_id = request.session['user_info']['blog__nid'] self.fields['category_id'].choices = models.Category.objects.filter( blog_id=blog_id).values_list('nid', 'title') self.fields['tag_id'].choices = models.Tag.objects.filter( blog_id=blog_id).values_list('nid', 'title')
class AddFrom(forms.Form): host = fields.ChoiceField( choices=((None, '请选择..'), (1, 'kvm1'), (2, 'kvm2'), (3, 'kvm3'), (4, 'kvm4'), (5, 'kvm5')), label='主机', label_suffix=':', widget=fields.Select( attrs={'class': 'form-control col-2'}), validators=[RegexValidator(r'[1-5]', '请选择待安装镜像的宿主机。')] ) ver = fields.ChoiceField( choices=((None, '请选择..'), (1, 'v59'), (2, 'v60'), (3, 'v70'), (4, 'v80')), label='系统版本', label_suffix=':', widget=fields.Select( attrs={'class': 'form-control col-2'}), validators=[RegexValidator(r'[1-5]', '请选择待安装镜像的版本类别。')] ) package = fields.CharField(label='镜像包', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control col-4', 'placeholder': '镜像包全称,如v59-rc01-006-marketing-20151119-iso.tar.gz', 'style': 'font-size: small'})) name = fields.CharField(label='虚拟机名称', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control col-4', 'placeholder': '请输入待创建的虚拟机名称', 'style': 'font-size: small'})) imgfile = fields.CharField(label='磁盘文件', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control col-4', 'placeholder': '请输入待创建的磁盘文件名称', 'style': 'font-size: small'})) ip = fields.CharField(label='IP', label_suffix=':', widget=fields.TextInput( attrs={'class': 'form-control col-4', 'placeholder': '请输入待指定的ip地址', 'style': 'font-size: small'}))
def __init__(self, *args, **kwargs): school_id = kwargs.pop('school_id') super(StudentModelForm, self).__init__(*args, **kwargs) stu_class_list = tuple( stumodels.StuClass.objects.filter(school_id=school_id)) stu_class_list = [(item.pk, item) for item in stu_class_list] stu_class = Ffields.ChoiceField(required=True, choices=stu_class_list, widget=Fwidgets.Select(attrs={ 'class': 'form-control', 'id': 'class' }), error_messages={"required": "请选择班级"}) grade_list = tuple( stumodels.Grade.objects.filter( stuclass__school_id=school_id).all().distinct()) grade_list = [(item.pk, item) for item in grade_list] grade_list.insert(0, (0, '--- 选择年级 ---')) grade = Ffields.ChoiceField(required=True, choices=grade_list, widget=Fwidgets.Select(attrs={ 'class': 'form-control', 'id': 'grade' })) self.fields['grade'] = grade self.fields['stu_class'] = stu_class
class VisualReportForm(forms.Form): visual_report_name = forms.CharField(widget=widgets.TextInput( attrs={'class': 'form-control'}, ), required=True, max_length=60, min_length=2, label='报表名称') is_down = fields.ChoiceField(initial=0, choices=((0, '是'), (1, '否')), widget=widgets.RadioSelect(), label='是否可下载') online = fields.ChoiceField(initial=0, choices=((0, '是'), (1, '否')), widget=widgets.RadioSelect(), label='是否上线') mid = fields.ChoiceField( initial=1, widget=widgets.Select(attrs={'class': 'form-control'}), label='菜单选择') def __init__(self, *args, **kwargs): super(VisualReportForm, self).__init__(*args, **kwargs) self.fields[ 'mid'].widget.choices = models.BdpDataVisualMenu.objects.all( ).values_list('mid', 'menu_name')
class AdvSearchPagesForm(SearchPagesForm): date_month = fields.ChoiceField(choices=MONTH_CHOICES) date_day = fields.ChoiceField(choices=DAY_CHOICES) lccn = fields.MultipleChoiceField(choices=[]) # state = fields.MultipleChoiceField(choices=[]) city = fields.MultipleChoiceField(_cities_options()) county = fields.MultipleChoiceField(_counties_options()) newspaper_type = fields.MultipleChoiceField(_types_options()) region = fields.MultipleChoiceField(_regions_options()) date1 = fields.CharField() date2 = fields.CharField() sequence = fields.CharField() ortext = fields.CharField() andtext = fields.CharField() nottext = fields.CharField() proxtext = fields.CharField() proxdistance = fields.ChoiceField(choices=PROX_CHOICES) # language = fields.ChoiceField() def __init__(self, *args, **kwargs): super(AdvSearchPagesForm, self).__init__(*args, **kwargs) self.date = self.data.get('date1', '') self.fields["city"].choices = self.cities self.fields["county"].choices = self.counties self.fields["newspaper_type"].choices = self.types self.fields["region"].choices = self.regions self.fields["lccn"].choices = self.titles # self.fields["state"].widget.attrs = {'id': 'id_states'} self.fields["date1"].widget.attrs = { "id": "id_date_from", "max_length": 10 } self.fields["date1"].initial = "" self.fields["date2"].widget.attrs = { "id": "id_date_to", "max_length": 10 } self.fields["date2"].initial = "" self.fields["proxdistance"].initial = "5" # self.fields["city"].widget.attrs = {"data-placeholder": "Click here to choose some Cities"} # self.fields["county"].widget.attrs = {"data-placeholder": "Click here to choose some Counties"} # self.fields["newspaper_type"].widget.attrs = {"data-placeholder": "Click here to choose some Types"} # self.fields["region"].widget.attrs = {"data-placeholder": "Click here to choose some Regions"} self.fields["lccn"].widget.attrs = {'id': 'id_lccns'} self.fields["sequence"].widget.attrs = { "id": "id_char_sequence", "size": "3" } self.fields["proxtext"].widget.attrs = { "id": "id_proxtext_adv", "class": "form-control" } self.fields["ortext"].widget.attrs = {"class": "form-control"} self.fields["andtext"].widget.attrs = {"class": "form-control"} self.fields["nottext"].widget.attrs = {"class": "form-control"}
class FM(forms.Form): # error_messages自定义错误显示信息。required/invalid/不能随便写,必须跟返回的obj.errors里面的code的值一样。如"code": "invalid",那么这里"invalid"就是key user = fields.CharField(error_messages={'required': '用户名不能为空'}, initial='sun', label='用户名', disabled=True) #widget用来引用插件,widgets.PasswordInput代表密码插件。 #这个插件有很多,input,select,radius,checkbox等都有。 # fields.CharField表示对字段验证,widget表示使用里面的某个插件 pwd = fields.SlugField(max_length=12, min_length=6, error_messages={ 'required': '密码不能为空', 'min_length': '太短了', 'max_length': '太长了', 'invalid': '只支持数字字母下划线减号' }, widget=widgets.PasswordInput) email = fields.EmailField(error_messages={ 'required': '用户名不能为空', 'invalid': '邮箱格式错误' }, initial='*****@*****.**') #可以定义input的类型,比如widgets.Textarea就是文本框,还可以定义属性,attrs可以定义里面的属性,样式等。 #引用文本框插件Textarea,并且给文本框定义样式。 msg = fields.CharField(required=False, error_messages={'required': '信息不能为空'}, widget=widgets.Textarea(attrs={ 'class': 'c1', 'name': 'msg' })) # phone=fields.CharField(validators=[RegexValdator(r'^[0-9]+$','请输入数字'),RegexValdator(r'^159[0-9]+$','数字必须以159开头')]) # 在页面上显示templates文件夹下面的所有文件 file = fields.FilePathField(path='templates') #下拉框 #单选框 c1 = fields.ChoiceField(choices=[(0, '北京'), (1, '上海'), (2, 'NewYork')], initial=2) #多选框 c2 = fields.MultipleChoiceField(choices=[(0, '北京'), (1, '上海'), (2, 'NewYork')], initial=[1, 2]) #单选按钮 c3 = fields.ChoiceField(choices=[(0, '北京'), (1, '上海'), (2, 'NewYork')], widget=widgets.RadioSelect) #单选select c4 = fields.CharField(widget=widgets.Select(choices=( (1, '上海'), (2, '北京'), ))) #单选勾选 c5 = fields.CharField(widget=widgets.CheckboxInput()) #多选checkbox c6 = fields.MultipleChoiceField(choices=( (1, '上海'), (2, '北京'), (3, '湖南'), ), widget=widgets.CheckboxSelectMultiple())
class SearchTitlesForm(forms.Form): state = fields.ChoiceField(choices=[], initial="") county = fields.ChoiceField(choices=[], initial="") city = fields.ChoiceField(choices=[], initial="") year1 = fields.ChoiceField(choices=[], label="from") year2 = fields.ChoiceField(choices=[], label="to") terms = fields.CharField(max_length=255) frequency = fields.ChoiceField(choices=FREQUENCY_CHOICES, initial="", label="Frequency:") language = fields.ChoiceField(choices=[], initial="", label="Language:") ethnicity = fields.ChoiceField(choices=[], initial="", label="Ethnicity Press:") labor = fields.ChoiceField(choices=[], initial="", label="Labor Press:") material_type = fields.ChoiceField(choices=[], initial="", label="Material Type:") lccn = fields.CharField(max_length=255, label="LCCN:") def __init__(self, *args, **kwargs): super(SearchTitlesForm, self).__init__(*args, **kwargs) current_year = datetime.date.today().year years = range(1690, current_year + 1, 10) if years[-1] != current_year: years.append(current_year) choices = [(year, year) for year in years] self.fields["year1"].choices = choices self.fields["year1"].widget.attrs["class"] = "norm" self.fields["year1"].initial = choices[0][0] self.fields["year2"].choices = choices self.fields["year2"].initial = choices[-1][0] self.fields["year2"].widget.attrs["class"] = "norm" language = [ ("", "Select"), ] language.extend( (l.name, l.name) for l in models.Language.objects.all()) self.fields["language"].choices = language ethnicity = [ ("", "Select"), ] ethnicity.extend( (e.name, e.name) for e in models.Ethnicity.objects.all()) self.fields["ethnicity"].choices = ethnicity labor = [ ("", "Select"), ] labor.extend((l.name, l.name) for l in models.LaborPress.objects.all()) self.fields["labor"].choices = labor material = [("", "Select")] material.extend( (m.name, m.name) for m in models.MaterialType.objects.all()) self.fields["material_type"].choices = material
class CreateIdcForm(forms.Form): """创建业务验证""" virIP = fields.GenericIPAddressField(required=True, widget=widgets.TextInput(attrs={'class': 'form-inline'}), error_messages={ 'required': '此项不能为空', 'invalid': '请输入正确的IP格式' }) physicalIP = fields.GenericIPAddressField(required=True, widget=widgets.TextInput(attrs={'class': 'form-inline'}), error_messages={'required': '此项不能为空', 'invalid': '请输入正确的IP格式' }) application = fields.CharField(required=True, widget=widgets.TextInput(attrs={'class': 'form-inline'}), error_messages={'required': '此项不能为空'}) port = fields.IntegerField(required=False, widget=widgets.TextInput(attrs={'class': 'form-inline'}), error_messages={'invalid': '请输入正确的端口格式'} ) component = fields.CharField(required=True, widget=widgets.TextInput(attrs={'class': 'form-inline'}), error_messages={ 'required': '此项不能为空', }) Bussiness_idc = fields.ChoiceField( choices=models.Bussiness.objects.values_list('id', 'name'), # choices=models.Idc.Bussiness_idc_id.objects.values_list('id','name'), widget=widgets.Select ) fuzai = fields.ChoiceField( choices=models.Idc.type_Lalancing, widget=widgets.Select ) principal = fields.CharField(required=True, widget=widgets.TextInput(attrs={'class': 'form-inline'}), error_messages={ 'required': '此项不能为空', }) note = fields.CharField(required=False, widget=widgets.TextInput(attrs={'class': 'form-inline'}), ) """业务表还有加自动更新""" def __init__(self, *args, **kwargs): super(CreateIdcForm, self).__init__(*args, **kwargs) self.fields['Bussiness_idc'].choices = models.Bussiness.objects.values_list('id', 'name')
class AuditLogForm(Form): """审计日志所需form""" list_per_page = fields.ChoiceField( choices=((10, 10), (25, 25), (50, 50), (100, 100)), widget=widgets.Select(attrs={ "id": "list_per_page", "class": "form-control" })) user = fields.ChoiceField(label="用户", widget=widgets.Select(attrs={ "class": "form-control", "style": "width:100%" }), required=False) bind_host = fields.ChoiceField( label="访问的主机", widget=widgets.Select(attrs={ "class": "form-control", "style": "width:100%" }), required=False) start_date = fields.DateField( label="起始日期", widget=widgets.DateInput(attrs={ "class": "date-picker form-control", "style": "width:100%" }), required=False) end_date = fields.DateField( label="终止日期", widget=widgets.DateInput(attrs={ "class": "date-picker form-control", "style": "width:100%" }), required=False) def __init__(self, *args, **kwargs): super(AuditLogForm, self).__init__(*args, **kwargs) user_choices = list( models.UserProfile.objects.values_list("id", "name")) user_choices.insert(0, ("", "------------------")) self.fields["user"].widget.choices = user_choices bind_host_needed_fields = [ "id", "host__ip_adr", "remote_user__username" ] bind_host_choices = list( models.BindHost.objects.select_related( *bind_host_needed_fields).values_list( *bind_host_needed_fields)) bind_host_choices = [(i[0], f"{i[2]}@{i[1]}") for i in bind_host_choices] bind_host_choices.insert(0, ("", "------------------")) self.fields["bind_host"].widget.choices = bind_host_choices
class WorkForms(Form): '工作表' title = fields.CharField(max_length=32, min_length=2, required=True, widget=widgets.TextInput(attrs={ 'class': "form-control", 'placeholder': "工作项目" })) content = fields.CharField(max_length=255, min_length=2, required=True, widget=widgets.Textarea(attrs={ 'class': "form-control", 'placeholder': "工作进度" })) main_response = fields.ChoiceField(widget=widgets.Select( attrs={'class': "form-control"})) sub_response = fields.MultipleChoiceField( widget=widgets.SelectMultiple(attrs={'class': "form-control"}), required=False) # create_time=fields.DateTimeField() status = fields.ChoiceField( widget=widgets.Select(attrs={'class': "form-control"}), choices=( (True, '是'), (False, '否'), )) def __init__(self, request, subtitle, *args, **kwargs): super(WorkForms, self).__init__(*args, **kwargs) self.request = request self.subtitle = subtitle print('----subtitle') print(self.subtitle) print('------request') print(self.request) print('-------args') print(args) print('------kwargs') print(kwargs) role_department_id = models.UserInfo.objects.filter( subtitle=self.subtitle).values('role_id', 'department_id', 'uid').first() print('---------role_department_id') print(role_department_id) userinfo = models.UserInfo.objects.filter( role_id=role_department_id.get('role_id'), department_id=role_department_id.get('department_id')).values( 'uid', 'username') print(userinfo) self.fields['main_response'].choices = models.UserInfo.objects.filter \ (role_id=role_department_id.get('role_id'), department_id=role_department_id.get('department_id')).values_list('uid', 'username') self.fields['sub_response'].choices = models.UserInfo.objects.filter \ (role_id=role_department_id.get('role_id'), department_id=role_department_id.get('department_id')).values_list('uid', 'username') self.fields['main_response'].initial = role_department_id.get('uid')
def answer_detail(request,class_id, qid): student_id = request.session['student_info']['id'] # 查看是否是当前问卷班级的学生 class_check = models.Student.objects.filter(id=student_id, cls_id=class_id).count() if not class_check: return redirect("/login/") # 检查该用户是否提交过 submit_check = models.Answer.objects.filter(stu_id=student_id, question__questionnaire_id=qid).count() if submit_check: return HttpResponse("你已经提交过了!") # 展示当前问卷的内容 # 获取当前问卷的问题列表 question_list = models.Question.objects.filter(questionnaire_id=qid) question_dict = {} for item in question_list: # 分别取出不同类型的问题 if item.tp == 1: question_dict['val_%s' % item.id] = fields.ChoiceField( label=item.caption, error_messages={"required": "不能为空"}, widget=widgets.RadioSelect, choices=[(i, i) for i in range(1, 11)] ) elif item.tp == 2: question_dict['option_id_%s' % item.id] = fields.ChoiceField( label=item.caption, error_messages={"required": "不能为空"}, widget=widgets.RadioSelect, choices=models.Option.objects.filter(qs_id=item.id).values_list("id", "name") ) else: question_dict['content_%s' % item.id] = fields.CharField( label=item.caption, error_messages={"required":"不能为空"}, widget=widgets.Textarea, # 调用func函数用来验证 validators=([func, ]) ) # 通过type创建Form类,,可以循环的创建数据,question_dict为字段 question_list_form = type("question_list_form", (Form,), question_dict) # 当get请求是,获取form对象,生成选项框 if request.method == "GET": form = question_list_form() return render(request, "answer_detail.html", {"question_list": question_list, "form": form}) else: # 验证用户提交的数据 form = question_list_form(request.POST) answer_obj = [] if form.is_valid(): for k, v in form.cleaned_data.items(): print(form.cleaned_data) t, qid = k.rsplit("_", 1) answer_dict = {"stu_id": student_id, "question_id": qid, t: v} answer_obj.append(models.Answer(**answer_dict)) models.Answer.objects.bulk_create(answer_obj) return HttpResponse("感谢您的参与!") return render(request, "answer_detail.html", {"question_list": question_list, "form": form})
class ProductForm(forms.Form): p_name = fields.CharField(max_length=50, error_messages={ 'required': '产品名称不能为空', 'max_length': '长度不能超过50个汉字', }) p_t_imgae = fields.CharField(error_messages={ 'required': '请上传图片', }) p_category_id = fields.IntegerField( required=False, widget=widgets.Select(attrs={'class': 'form-control'}), error_messages={'invalid': '无效选择'}) p_service_id = fields.IntegerField(required=False, widget=widgets.Select( attrs={'class': 'form-control'}, ), error_messages={ 'required': '服务类型必须选择一个', 'invalid': '无效选择' }) p_putaway = fields.ChoiceField( choices=((1, '上架'), (0, '下架')), widget=widgets.Select(attrs={'class': 'form-control'}), error_messages={'invalid': '无效选择'}) p_top = fields.ChoiceField( choices=((0, '不推荐'), (1, '推荐')), widget=widgets.Select(attrs={'class': 'form-control'}), error_messages={'invalid': '无效选择'}) p_business_id = fields.IntegerField(error_messages={ 'required': '业务类型必须选择一个', 'invalid': '无效选择' }) p_price = fields.FloatField(error_messages={ 'required': '价格不能为空', 'invalid': '请输入数字' }) p_market_price = fields.FloatField(required=False, error_messages={'invalid': '请输入数字'}) p_seo_keyword = fields.CharField( required=False, max_length=100, error_messages={'max_length': '不能超过100个字符'}) p_seo_description = fields.CharField( required=False, max_length=300, error_messages={'max_length': '不能超过300个字符'}) p_details = fields.CharField(error_messages={'required': '产品内容内容不能为空'}) def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) cate_obj = models.ProductCategory.objects.all() self.fields['p_category_id'].widget.choices = get_cate_tupe(cate_obj) self.fields[ 'p_service_id'].widget.choices = models.ProductService.objects.values_list( 'id', 'name')
class HostForm(Form): hostname = fields.CharField( #required=True, #是否允许为空 error_messages={'required': '主机名不能为空'}, # 加样式是 通过 form-control 修改 widget=widgets.TextInput(attrs={'class': 'form-control'}), ) cpu = fields.CharField( required=True, error_messages={'required': '核心数不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'}), ) mem = fields.CharField( required=True, error_messages={'required': '内存大小不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'}), ) speed = fields.CharField( required=True, #error_messages={'required':'不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'}), ) eth0_network = fields.CharField( required=True, error_messages={'required': '网卡信息不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'}), ) source_id = fields.ChoiceField( required=True, #error_messages={'required':'不能为空'}, choices=[], #下拉框 widget=widgets.Select(attrs={'class': 'form-control'}), ) region_id = fields.ChoiceField( required=True, choices=[], # error_messages={'required':'不能为空'}, widget=widgets.Select(attrs={'class': 'form-control'}), ) state = fields.CharField( required=True, #choices=[], error_messages={'required': '不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'}), ) messages = "温馨提示,这里请填写正确的数字, (1, 'Running'),(2, '下线'), (3, '关机'),(4, '删除'), (5, '故障')," def __init__(self, *args, **kwargs): '每次都默认执行初始化,保证在数据库拿到的数据是最新的' super(HostForm, self).__init__(*args, **kwargs) self.fields['source_id'].choices = models.Source.objects.values_list( 'id', 'name') self.fields['region_id'].choices = models.Region.objects.values_list( 'id', 'name')
def __init__(self, *args, **kwargs): list_fields = ( fields.ChoiceField(required=False, choices=length_hour_choices), fields.ChoiceField(required=False, choices=minute_choices), ) super(TimeDropDownField, self). __init__( fields=list_fields, *args, **kwargs )
def __init__(self, *args, **kwargs): year = date.today().year flds = (fields.ChoiceField(label='year', choices=[(x,x) for x in range(year, year+10)]), fields.ChoiceField(label='month', choices=[(x,str(x).zfill(2)) for x in range(1, 13)]) ) super(CardExpirationField, self).__init__( fields = flds, *args, **kwargs ) self.widget = CardExpirationWidget(widgets = [flds[0].widget, flds[1].widget])
class SearchResultsForm(forms.Form): rows = fields.ChoiceField(label="Rows", choices=RESULT_ROWS) sort = fields.ChoiceField(choices=RESULT_SORT) # add classes rows.widget.attrs["class"] = "form-control" sort.widget.attrs["class"] = "form-control" def __init__(self, *args, **kwargs): super(SearchResultsForm, self).__init__(*args, **kwargs) self.fields["rows"].initial = kwargs.get("rows", "20") self.fields["sort"].initial = kwargs.get("sort", "relevance")
class OrderAddForm(forms.Form): product_id = fields.IntegerField( widget=widgets.Select(attrs={'class': 'form-control'}), error_messages={'required': '必须选择一个'}) cprice = fields.FloatField(error_messages={'required': '价格不能为空'}) number = fields.IntegerField(error_messages={'required': '数量不能为空'}) order_state = fields.ChoiceField(choices=((0, '待付款'), (1, '待服务'), (2, '服务中'), (3, '服务完成'))) name = fields.CharField(error_messages={'required': '姓名不能为空'}) phone = fields.IntegerField(error_messages={'required': '手机号码不能为空'}) payment = fields.ChoiceField(choices=((0, '支付宝'), (1, '微信'), (2, '线下支付'), (3, '网银支付')))
class EmblemForm(StarkModelForm): issuer = fields.ChoiceField(widget=widgets.RadioSelect(), label='颁发者', choices=((1, '老师'), (2, '家长'), (3, '两者皆可'))) classification = fields.ChoiceField(widget=widgets.RadioSelect(), label='徽章分类', choices=((1, '鼓励与表扬'), (2, '惩罚与批评'))) scope = fields.ChoiceField(required=False, widget=widgets.RadioSelect(), label='颁发范围', choices=((1, '校级别'), (2, '班级'))) subject = forms.ModelMultipleChoiceField( required=False, label='关联课程', queryset=Course.objects.all(), widget=widgets.CheckboxSelectMultiple()) grade = forms.ModelMultipleChoiceField( required=False, label='关联年级', queryset=Grade.objects.all(), widget=widgets.CheckboxSelectMultiple()) icon = fields.FileField( widget=fields.FileInput(attrs={'style': 'display:none'}), label='徽章图片') emblem_type = forms.ModelChoiceField( required=False, label='徽章类型', queryset=EmblemType.objects.exclude(id__in=[ item.pid.id for item in EmblemType.objects.filter(pid__isnull=False) ])) is_custom = fields.ChoiceField(widget=widgets.RadioSelect(), label='是否允许自定制', choices=((True, '允许'), (False, '禁止')), initial=False) class Meta: model = Emblem fields = ( 'emblem_name', 'icon', 'description', 'classification', 'scope', 'is_custom', 'issuer', 'subject', 'emblem_type', 'grade', )
class CreatAssetForm(Form): hostname = fields.CharField( required=True, min_length=1, max_length=20, error_messages={'required': '*主机名不能为空'}, widget=widgets.TextInput(attrs={'name': 'hostname'})) ip = fields.GenericIPAddressField( required=True, error_messages={ 'required': '*IP不能为空', 'invalid': '*IP格式错误' }, widget=widgets.TextInput(attrs={'name': 'ip'})) port = fields.CharField(required=True, min_length=1, max_length=5, error_messages={'required': '*端口不能为空'}, widget=widgets.TextInput(attrs={'name': 'port'})) model = fields.CharField(required=True, min_length=1, max_length=20, error_messages={'required': '*类型不能为空'}, widget=widgets.TextInput(attrs={'name': 'model'})) # fields.EmailField() # fields.GenericIPAddressField(protocol='ipv4') env_id = fields.ChoiceField( choices=[], widget=widgets.Select(attrs={'name': 'env_id'})) hardware = fields.CharField( required=True, min_length=1, max_length=20, error_messages={'required': '*硬件配置不能为空'}, widget=widgets.TextInput(attrs={'name': 'hardware'})) bussiness_id = fields.ChoiceField( required=True, choices=[], error_messages={'required': '*主机所属业务线不能为空'}, widget=widgets.Select(attrs={'name': 'bl_id'})) def __init__(self, *args, **kwargs): super(CreatAssetForm, self).__init__(*args, **kwargs) # self.fields已经有所有拷贝的字段 # print(Env.objects.values_list('id', 'name')) # print(UserInfo.objects.values_list('id', 'username')) self.fields['env_id'].choices = Env.objects.values_list('id', 'name') self.fields[ 'bussiness_id'].choices = BussinessLine.objects.values_list( 'id', 'name')
class TransferInForm(Form): """党员转入Form""" username = fields.CharField( min_length=6, max_length=13, error_messages={ 'required': '用户名不能为空', 'invalid': '用户名格式有误,请重新输入' }, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入用户名(6-13位)" })) member_name = fields.RegexField( regex=r'^[\u4E00-\u9FA5]{2,6}$', max_length=32, error_messages={ 'required': '姓名不能为空', 'invalid': '姓名格式有误,请重新输入' }, widget=fields.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入姓名(2-6个汉字)" })) member_gender = fields.ChoiceField(choices=(('男', '男'), ('女', '女')), initial='男', widget=widgets.Select()) member_status = fields.ChoiceField(choices=(('正式党员', '正式党员'), ('预备党员', '预备党员')), initial='正式党员', widget=widgets.Select()) in_date = forms.DateField(error_messages={'required': '转入日期不能为空'}, widget=forms.TextInput(attrs={ 'class': 'form-control', 'type': 'date' })) come_from_party = fields.CharField( max_length=256, error_messages={'required': '转自组织内容不能为空'}, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入转自什么组织" }))
class IpList( Form, ): # id = fields.UUIDField(required=True) hostname = fields.CharField(required=True) ip = fields.GenericIPAddressField(required=True) product = fields.ChoiceField(choices=[('service', '服务器'), ('switch', '交换机'), ('router', '路由器')], widget=widgets.Select) group = fields.CharField(required=True) user = fields.CharField(required=True) passwd = fields.CharField(required=True) system = fields.ChoiceField(choices=[('linux', 'linux'), ('windows', 'windows')], widget=widgets.Select)
class SearchPagesForm(SearchPagesFormBase): # locations city = fields.ChoiceField(label="City") county = fields.ChoiceField(label="County") state = fields.ChoiceField(label="State") # date date1 = fields.CharField() date2 = fields.CharField() date_day = fields.ChoiceField(choices=DAY_CHOICES) date_month = fields.ChoiceField(choices=MONTH_CHOICES) # text andtext = fields.CharField(label="All of the words") ortext = fields.CharField(label="Any of the words") phrasetext = fields.CharField(label="With the phrase") proxtext = fields.CharField(label="Words near each other") proxdistance = fields.ChoiceField(choices=PROX_CHOICES) # misc lccn = fields.CharField(label="LCCN") sequence = fields.CharField(label="Page Number") titles = fields.MultipleChoiceField(choices=[]) # filters frequency = fields.ChoiceField(label="Frequency") language = fields.ChoiceField(label="Language") form_control_items = [ city, county, state, date1, date2, date_day, date_month, andtext, ortext, phrasetext, proxtext, proxdistance, lccn, sequence, titles, language, frequency ] for item in form_control_items: item.widget.attrs["class"] = "form-control" def __init__(self, *args, **kwargs): super(SearchPagesForm, self).__init__(*args, **kwargs) self.date = self.data.get('date1', '') self.fields["titles"].widget.attrs.update({'size': '8'}) self.fields["titles"].choices = self.titles lang_choices = [ ("", "All"), ] lang_choices.extend((l, models.Language.objects.get(code=l).name) for l in settings.SOLR_LANGUAGES) self.fields["language"].choices = lang_choices # locations self.fields["city"].choices = _distinct_values(models.Place, "city", "City") self.fields["county"].choices = _distinct_values( models.Place, "county", "County") self.fields["state"].choices = _distinct_values( models.Place, "state", "State") # filters self.fields["frequency"].choices = _distinct_values( models.Title, "frequency", "Select")
class PermissionModelForm(ModelForm): url = fields.ChoiceField() # 若该字段名和Permission中的某字段重名,则会将该字段替换,不重名,则添加新的 # from pro_crm.urls import urlpatterns # url.choices=get_all_url(urlpatterns,"/",True) #此种赋值方式1:会使urlpatterns提前执行,引发错误 # 2.当新增url时,不能时时刷新,因为PermissionModelForm声明时会取一遍url, # 当用其new对象时,不会再去获取新的url,因此需要将获取url的逻辑写在__init__中 class Meta: model = models.Permission fields = "__all__" def clean_urls(self,url_list=None): """将已存在于权限列表的url从url_list中移除,添加页面无需显示""" exist_urls = [obj.url for obj in models.Permission.objects.all()] result = [] for item in url_list: if item[0] not in exist_urls: result.append(item) return result def __init__(self, *args, **kwargs): super(PermissionModelForm, self).__init__(*args, **kwargs) from finance.urls import urlpatterns self.fields["url"].choices = self.clean_urls(get_all_url(urlpatterns, "/", True)) if self.instance and self.instance.url: #要把该obj的url给添加进去 self.fields["url"].choices.append((self.instance.url,self.instance.url,))
class ShippingMethodForm(DialogForm): scope_prefix = 'data.shipping_method' shipping_modifier = fields.ChoiceField(label=_("Shipping Method"), widget=RadioSelect(renderer=RadioFieldRenderer, attrs={'ng-change': 'upload()'}) ) def __init__(self, *args, **kwargs): choices = [m.get_choice() for m in cart_modifiers_pool.get_shipping_modifiers() if not m.is_disabled(kwargs['cart'])] self.base_fields['shipping_modifier'].choices = choices if len(choices) == 1: # with only one choice, initialize with it try: kwargs['initial']['shipping_modifier'] = choices[0][0] except KeyError: pass super(ShippingMethodForm, self).__init__(*args, **kwargs) def has_choices(self): return len(self.base_fields['shipping_modifier'].choices) > 0 @classmethod def form_factory(cls, request, data, cart): cart.update(request) shipping_method_form = cls(data=data, cart=cart) if shipping_method_form.is_valid(): cart.extra.update(shipping_method_form.cleaned_data) return shipping_method_form