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 MulvisualizeForm(ModelForm): nodelist_choices_list = [] for value in Nodename.objects.values_list('nodename'): choice = (value[0], value[0]) nodelist_choices_list.append(choice) nodelist_choices = tuple(nodelist_choices_list) nodename = fields.MultipleChoiceField( choices=nodelist_choices, widget=forms.widgets.SelectMultiple(attrs={'name': 'nodenames', 'id': 'nodenamesid', 'class': "selectpicker"}) ) metriclist_choices_list = [] for value in Metric.objects.values_list('metric'): choice = (value[0], value[0]) metriclist_choices_list.append(choice) metriclist_choices = tuple(metriclist_choices_list) metric = fields.MultipleChoiceField( choices=metriclist_choices, widget=forms.widgets.SelectMultiple(attrs={'name': 'metrics', 'id': 'metricsid', 'class': "selectpicker"}) ) class Meta: model = Mulvisualize fields = ['dedimensionname'] widgets = { 'dedimensionname': TextInput(attrs={'name':'dedimensionname'}), }
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 Test_Form(Form): name = fields.CharField() text = fields.CharField(widget=widgets.Textarea, ) age = fields.CharField(widget=widgets.CheckboxInput) hobly = fields.MultipleChoiceField(choices=[(1, '篮球'), (2, "足球"), (3, "高俅")], widget=widgets.CheckboxSelectMultiple) sex = fields.MultipleChoiceField(choices=[(1, '男'), (2, '女')], widget=widgets.RadioSelect)
class TeacherForm(Form): name = fields.CharField(required=True, error_messages={'required': '用户名不能为空'}, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'id': 'name' })) age = fields.IntegerField(required=True, error_messages={'required': '年龄不能为空'}, widget=widgets.NumberInput(attrs={ 'class': 'form-control', 'id': 'age' })) sex = fields.CharField(required=True, error_messages={'required': '性别不能为空'}, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'id': 'sex' })) tel = fields.IntegerField(required=True, error_messages={'required': '电话不能为空'}, widget=widgets.NumberInput(attrs={ 'class': 'form-control', 'id': 'tel' })) salary = fields.IntegerField(required=True, error_messages={'required': '薪水不能为空'}, widget=widgets.NumberInput(attrs={ 'class': 'form-control', 'id': 'salary' })) class_list = fields.MultipleChoiceField( choices=models.Classes.objects.values_list("id", "name"), widget=widgets.SelectMultiple(attrs={ 'class': 'form-control', 'id': 'classes' })) course_list = fields.MultipleChoiceField( choices=models.Course.objects.values_list("id", "name"), widget=widgets.SelectMultiple(attrs={ 'class': 'form-control', 'id': 'course' })) userType = fields.ChoiceField(choices=models.UserType.objects.values_list( "id", "name"), widget=widgets.Select(attrs={ 'class': 'form-control', 'id': 'usertype' }))
class UserForm(forms.Form): id = fields.IntegerField(required=False) username = forms.CharField( min_length=5, max_length=32, required=False, error_messages={'required': '不能为空', 'max_length': '不能大于32位', 'min_length': '不能小于5位'}) password = forms.CharField( min_length=5, max_length=32, required=False, error_messages={'required': '不能为空', 'max_length': '不能大于32位', 'min_length': '不能小于5位'}) name = forms.CharField() role = fields.ChoiceField(choices=[(1, 'admin'), (2, 'user'), ]) host = fields.MultipleChoiceField(required=False) host_group = fields.MultipleChoiceField(required=False) # 判断用户名是否重复 def clean_username(self): obj_username = models.User.objects.filter(username=self.cleaned_data['username']) if not obj_username: return self.cleaned_data['username'] else: if 'id' in self.cleaned_data.keys(): if obj_username.filter(id=self.cleaned_data['id']): return self.cleaned_data['username'] raise ValidationError('用户名已存在') def clean(self): # 防止修改用户名 if self.cleaned_data['id']: if self.cleaned_data['username']: raise ValidationError('用户名不能修改') else: self.cleaned_data['username'] = models.User.objects.get(id=self.cleaned_data['id']).username else: # 新添加用户时,用户名密码不能为空,修改用户时可以不修改密码 if not self.cleaned_data['username']: raise ValidationError('用户名不能为空') if not self.cleaned_data['password']: raise ValidationError('密码不能为空') # 如果主机和组机组为空时,把key从字典中去掉 if not self.cleaned_data['host']: self.cleaned_data.pop('host') if not self.cleaned_data['host_group']: self.cleaned_data.pop('host_group') # 不重启服务的情况下获取到最新的主机和主机组列表 def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['host'].choices = models.Host.objects.values_list('id', 'host_name') self.fields['host_group'].choices = models.HostGroup.objects.values_list('id', 'name')
class ArticleForm(Form): title = fields.CharField(widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'TITLE' })) summary = fields.CharField(widget=widgets.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'SUMMARY' })) content = fields.CharField(widget=widgets.Textarea( attrs={'id': 'kind-editor'})) type_id = fields.IntegerField(widget=widgets.RadioSelect( choices=models.Article.type_choices, attrs={'class': "form-radio"}), label="Type") category_id = fields.ChoiceField( choices=[], widget=widgets.RadioSelect(attrs={'class': "form-radio"}), label="Category", ) tags = fields.MultipleChoiceField( choices=[], required=False, widget=widgets.CheckboxSelectMultiple(attrs={'class': "form-radio"})) 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['tags'].choices = models.Tag.objects.filter( blog_id=blog_id).values_list('nid', 'title')
class ArticleForm(forms.Form): title = fields.CharField( widget=widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '文章标题'}) ) summary = fields.CharField( widget=widgets.Textarea(attrs={'class': 'form-control', 'placeholder': '文章简介', 'rows': '3'}) ) content = fields.CharField( widget=widgets.Textarea(attrs={'class': 'kind-content'}) ) article_type_id = fields.IntegerField( widget=widgets.RadioSelect(choices=models.Article.type_choices) ) category_id = fields.ChoiceField( choices=[], widget=widgets.RadioSelect ) tag = fields.MultipleChoiceField( choices=[], widget=widgets.CheckboxSelectMultiple ) 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.Article.objects.filter(blog_id=blog_id).values_list('nid', 'title') self.fields['tag'].choices = models.Article.objects.filter(blog_id=blog_id).values_list('nid', 'title')
class FieldsConfigEditForm(CremeModelForm): hidden = fields.MultipleChoiceField( label=_('Hidden fields'), choices=(), required=False, ) class Meta(CremeModelForm.Meta): model = FieldsConfig def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) instance = self.instance hidden_f = self.fields['hidden'] hidden_f.choices = FieldsConfig.objects.field_enumerator( instance.content_type.model_class(), ).choices() if instance.pk: hidden_f.initial = [f.name for f in instance.hidden_fields] def clean(self, *args, **kwargs): cdata = super().clean(*args, **kwargs) if not self._errors: HIDDEN = FieldsConfig.HIDDEN self.instance.descriptions = [(field_name, { HIDDEN: True }) for field_name in self.cleaned_data['hidden']] return cdata
class FoodForm(Form): meals = fields.MultipleChoiceField( choices=meal_choices(), widget=widgets.CheckboxSelectMultiple, help_text="If you don't have a food bursary, meal prices are: " "Breakfast {breakfast} USD, Lunch {lunch} USD, " "Dinner {dinner} USD.".format(**MEAL_PRICES), required=False, ) def __init__(self, *args, instance, **kwargs): super().__init__(*args, **kwargs) self.instance = instance self.helper = FormHelper() self.helper.include_media = False self.helper.layout = Layout( Field('meals', id='meals'), HTML('<div class="alert alert-success">' 'Total: USD$<span id="total">0.00</span>. ' '<span style="display: none">' 'Difference: USD$<span id="delta">0.00</span>' '</span></div>'), ButtonHolder( Submit('save', 'Save'), HTML( '<a href="{}" class="btn btn-secondary">Cancel</a>'.format( reverse( 'front_desk.check_in', kwargs={'username': self.instance.user.username}, )))), )
class FM(forms.Form): # 通过form生成HTML页面 user = fields.CharField( error_messages={'required': '用户名不能为空'}, widget=widgets.Textarea(attrs={'class': 'c1'}), label='用户名', ) pwd = fields.CharField(max_length=32, min_length=6, error_messages={ 'required': '密码不能为空', 'min_length': '密码最少为6个字符', 'max_length': '密码最多为32个字符' }, widget=widgets.PasswordInput(attrs={'class': 'c2'})) email = fields.EmailField(error_messages={ 'required': '邮箱不能为空.', 'invalid': "邮箱格式错误" }) f = fields.FileField(allow_empty_file=True) city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class FM(forms.Form): user = fields.CharField(error_messages={'required': '用户名不能为空'}, widget=widgets.Input(attrs={'class': 'c1'}), label="用户名") pwd = fields.CharField(max_length=12, min_length=6, error_messages={ 'required': '密码不能为空', 'max_length': '密码长度不能大于12位', 'min_length': '密码长度不能小于6位' }, widget=widgets.PasswordInput(attrs={'class': 'c2'}), label="密码") email = fields.EmailField(error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }, label="邮箱") f = fields.FileField(allow_empty_file=False) p = fields.FilePathField(path='app01') # 列出app01目录下所有文件 city1 = fields.ChoiceField(choices=[(0, '北京'), (1, '吉林'), (2, '银川')]) city2 = fields.MultipleChoiceField(choices=[(0, '广东'), (1, '深圳'), (2, '东莞')])
class ArticleForm(django_forms.Form): title = django_fields.CharField( widget=django_widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': '文章标题' }), error_messages={'required': '标题不能为空.'}) content = django_fields.CharField( widget=django_widgets.Textarea(attrs={ 'class': 'form-control', 'placeholder': '文章简介', 'rows': '3' }), error_messages={'required': '简介不能为空.'}) detail = django_fields.CharField( widget=django_widgets.Textarea(attrs={'class': 'kind-content'}), error_messages={'required': '内容不能为空.'}) category_id = django_fields.IntegerField( widget=django_widgets.RadioSelect( choices=models.Article.category_choice), error_messages={'required': '请选择一个分类.'}) tags = django_fields.MultipleChoiceField( choices=[], widget=django_widgets.CheckboxSelectMultiple, error_messages={'required': '请选择标签.'}) def __init__(self, request, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) blog_id = request.session['user_info']['blog__nid'] self.fields['tags'].choices = models.Tag.objects.filter( blog_id=blog_id).values_list('nid', 'caption')
class LoginForm(Form): name = fields.CharField( label='用户名', required=True, error_messages={ 'required':'用户名不能为空' }, widget=widgets.TextInput(attrs={'class':'form-control'}) ) pwd = fields.CharField( label='密码', required=True, error_messages={ 'required': '密码不能为空' }, widget=widgets.PasswordInput(attrs={'class':'form-control'}) ) email = fields.EmailField( label="邮箱", required=True, error_messages={ 'required':"邮箱不能为空" }, widget=widgets.EmailInput(attrs={'class':'form-control'}) ) roles = fields.MultipleChoiceField( label="组名", required=False, error_messages={ 'required':'组名不能为空' }, choices=role_querset,#2,4 widget=widgets.SelectMultiple(attrs={'class':'form-control'}) )
class FM(forms.Form): # 字段本身只做验证 user = fields.CharField( error_messages={'required': '用户名不能为空.'}, widget=widgets.Textarea(attrs={'class': 'c1'}), label="用户名", ) pwd = fields.CharField(max_length=12, min_length=6, error_messages={ 'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12' }, widget=widgets.PasswordInput(attrs={'class': 'c2'})) email = fields.EmailField(error_messages={ 'required': '邮箱不能为空.', 'invalid': "邮箱格式错误" }) f = fields.FileField() # p = fields.FilePathField(path='app01') city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class ArticleForm(Form): def __init__(self, val, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) self.val = val self.fields['category_id'].choices = models.Category.objects.filter( blog__user=self.val).values_list('nid', 'title').all() self.fields['tags'].choices = models.Tag.objects.filter( blog__user=self.val).values_list('nid', 'title').all() print(self.val) title = fields.CharField(max_length=64) summary = fields.CharField(max_length=128) article_type_id = fields.IntegerField(widget=widgets.RadioSelect( choices=models.Article.type_choices)) category_id = fields.ChoiceField(widget=widgets.RadioSelect) tags = fields.MultipleChoiceField(widget=widgets.CheckboxSelectMultiple) content = fields.CharField(widget=widgets.Textarea(attrs={'id': 'i1'})) def clean_content(self): old = self.cleaned_data['content'] from utils.xss import xss return xss(old)
class F1Form(forms.Form): #required 默认不为空 user = fields.CharField(max_length=18, min_length=6, required=True, error_messages={ "required": "用户名不能为空", "max_length": "用户名太长了", "min_length": "用户名太短了", }) pwd = fields.CharField(required=True, min_length=6, error_messages={ "required": "密码不能为空", "min_length": "密码太短了", }) age = fields.IntegerField(required=True) email = fields.EmailField(required=True, min_length=8, error_messages={ "required": "邮箱不能为空", "min_length": "密码太短了", "invalid": "邮箱格式错误" }) city = fields.ChoiceField( choices=[(1, "上海"), (2, "广州")], initial=1 #默认选择 ) bobby = fields.MultipleChoiceField(choices=[(1, "刚良"), (2, "附件"), (3, "你的")], )
class FORM(forms.Form): user = fields.CharField(error_messages={'required': '用户名不能为空'}, ) pwd = fields.CharField( max_length=12, min_length=6, error_messages={ 'required': '密码不能为空', 'max_length': '密码长度不能大于12', 'min_length': '密码长度不能小于6' }, widget=widgets.PasswordInput(attrs={'class': 'pas'})) email = fields.EmailField(error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }) remark = fields.CharField(required=False, label="备注", initial="备注信息", widget=widgets.Textarea(attrs={'class': 'user'})) f = fields.FileField() # p = fields.FilePathField(path='app01') city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class UserForm(Form): '''生成form表单''' username = fields.CharField( min_length=4, max_length=16, error_messages={'required':'用户名不能为空'}, # error_messages={'required': '邮箱不能为空','invalid':'邮箱格式错误'}, 格式错误范例 # 比如邮箱 ip ) password = fields.CharField( min_length=2, max_length=8, error_messages={'required':'密码不能为空',} ) ut_id = fields.ChoiceField( choices=[] ) role_id = fields.MultipleChoiceField( choices=[] ) def __init__(self,*args,**kwargs): super(UserForm,self).__init__(*args,**kwargs) # self.fields已经有所有拷贝的字段 self.fields['ut_id'].choices = models.UserType.objects.values_list('id','title') self.fields['role_id'].choices = models.Role.objects.values_list('id','caption')
class ArticlePost(forms.Form): """ 文章表单 """ title = fields.CharField(widget=widgets.TextInput(attrs={ "class": 'form-control', "placeholder": '请输入文章标题' })) summary = fields.CharField(widget=widgets.Textarea( attrs={ "class": 'form-control', "placeholder": '请输入文章简介', "rows": '3' })) body = fields.CharField(widget=widgets.Textarea( attrs={"class": 'kind-content'})) article_type_id = fields.IntegerField(widget=widgets.ChoiceWidget( choices=models.Article.type_choice)) category_id = fields.ChoiceField(choices=[], widget=widgets.RadioSelect) tags = fields.MultipleChoiceField(choices=[], widgets=widgets.CheckboxSelectMultiple) def __init__(self, request, *args, **kwargs): super(ArticlePost, self).__init__(*args, **kwargs) blog_id = request.session['user_info']['blog__nid'] self.fields['category_id'].choices = \ models.Category.objects.filter(blog=blog_id).values_list('nid', 'title') self.fields['tags'].choices = \ models.Tag.objects.filter(blog=blog_id).values_list('nid', 'title')
class ArticleForm(Form): def __init__(self, request, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) blog_id = request.session['user_info']['blog'] self.fields[ 'article_classification_id'].choices = Classification.objects.filter( blog_id=blog_id).values_list('id', 'title') self.fields['tags'].choices = Tags.objects.filter( blog_id=blog_id).values_list('id', 'title') publish = 0 title = fields.CharField(widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': '文章标题' })) summary = fields.CharField(widget=widgets.Textarea( attrs={ 'class': 'form-control', 'placeholder': '文章简介', 'rows': '3' })) detail = fields.CharField(widget=widgets.Textarea( attrs={'class': 'kind-content'})) # img = fields.ImageField() article_type_id = fields.IntegerField(widget=widgets.RadioSelect( choices=Article.type_choices)) article_classification_id = fields.ChoiceField(choices=[], widget=widgets.RadioSelect) img = fields.FileField(required=False) tags = fields.MultipleChoiceField(choices=[], widget=widgets.CheckboxSelectMultiple)
class ArticleForm(django_forms.Form): title = django_fields.CharField( widget=django_widgets.TextInput(attrs={'class': 'form-control', 'placeholder': '文章标题', 'required': 'required'}) ) content = django_fields.CharField( widget=django_widgets.Textarea(attrs={'class': 'kind-content', 'id': 'kind-content', 'style': 'overflow:auto;', 'required': 'required'}) ) category_id = django_fields.ChoiceField( choices=[], widget=django_widgets.RadioSelect, required=1 ) tags = django_fields.MultipleChoiceField( choices=[], widget=django_widgets.CheckboxSelectMultiple, required=1 ) def __init__(self, request, *args, **kwargs): super(ArticleForm, self).__init__(*args, **kwargs) user = models.UserInfo.objects.filter(username=request.user).first() self.fields['category_id'].choices = models.Category.objects.filter(blog=user.blog).values_list('nid', 'title') self.fields['tags'].choices = models.Tag.objects.filter(blog=user.blog).values_list('nid', 'title')
def formfield(self, **kwargs): """ This returns the correct formclass without calling super Returns select_multiple_field.forms.SelectMultipleFormField """ defaults = { 'required': not self.blank, 'label': capfirst(self.verbose_name), 'help_text': self.help_text } if self.has_default(): if callable(self.default): defaults['initial'] = self.default defaults['show_hidden_initial'] = True else: defaults['initial'] = self.get_default() if self.choices: # Django normally includes an empty choice if blank, has_default # and initial are all False, we are intentially breaking this # convention include_blank = self.blank defaults['choices'] = self.get_choices(include_blank=include_blank) # Many of the subclass-specific formfield arguments (min_value, # max_value) don't apply for choice fields, so be sure to only pass # the values that SelectMultipleFormField will understand. for k in kwargs.keys(): if k not in UNDERSTANDABLE_FIELDS: del kwargs[k] defaults.update(kwargs) return fields.MultipleChoiceField(**defaults)
class FM(forms.Form): user = fields.CharField( error_messages={'required': '用户名不能为空'}, label='用户名', widget=widgets.Input( attrs={'class': 'c1'} ), #其实就是类型,可以是input 可以是textarea,可以是select; attrs 为该标签加上class=c1的样式 # widget=widgets.Textarea ) pwd = fields.CharField( max_length=12, min_length=6, error_messages={ 'required': '密码不能为空.', 'min_length': '密码长度不能小于6', "max_length": '密码长度不能大于12' }, #自定义错误提示信息 label='密码', widget=widgets.PasswordInput) email = fields.EmailField( error_messages={ 'required': '邮箱不能为空.', 'invalid': "邮箱格式错误" }, label='邮箱', ) f = fields.FileField(allow_empty_file=False) city1 = fields.ChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')]) city2 = fields.MultipleChoiceField(choices=[(0, '上海'), (1, '广州'), (2, '东莞')])
class ArticleForm(django_forms.Form): title =django_fields.CharField( widget=django_widgets.TextInput(attrs={'class':'form-control','placeholder':'文章标题'}) ) summary = django_fields.CharField( widget=django_widgets.Textarea(attrs={'class':'form-control','placeholder':'文章简介','rows':'3'}) ) content = django_fields.CharField( widget= django_widgets.Textarea(attrs={'class':'kind-content'}) ) article_type_id = django_fields.IntegerField( widget=django_widgets.RadioSelect(choices=models.Article.type_choices) ) category_id = django_fields.ChoiceField( choices=[], widget=django_widgets.RadioSelect ) tags = django_fields.MultipleChoiceField( choices=[], widget=django_widgets.CheckboxSelectMultiple ) # 主要是为了实现数据库的实时更新(初始化函数中加上数据的获取) 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') print(self.fields['category_id']) #<django.forms.fields.ChoiceField object at 0x035E0B30> print(self.fields['category_id'].choices) # [(1, '.NET'), (2, '领域驱动'), (3, 'python'), (4, '设计模式'), (5, 'letCode')] self.fields['tags'].choices = models.Tag.objects.filter(blog_id=blog_id).values_list('nid','title')
class ServiceForm(Form): """ 业务线表单验证 """ def __init__(self, *args, **kwargs): super(ServiceForm, self).__init__(*args, **kwargs) self.fields['idc_id'].choices = models.Idc.objects.values_list( "id", "idc") self.fields['owner_id'].choices = models.User.objects.values_list( "id", "username") print("*" * 50) print(self.fields['idc_id'].choices) print(self.fields['owner_id'].choices) name = fields.CharField(required=True, label=u'业务线名称', max_length=32, error_messages={"required": "业务线名称不能为空!"}, widget=widgets.TextInput(attrs={ 'class': 'form-control', 'placeholder': u'业务线名称' })) idc_id = fields.ChoiceField( required=True, label=u'所属机房', choices=[], widget=widgets.Select(attrs={'class': 'form-control'})) owner_id = fields.MultipleChoiceField( required=True, choices=[], error_messages={'required': "负责人不能为空!"}, widget=widgets.SelectMultiple(attrs={'class': 'form-control'}))
class UserForm(Form): username = fields.CharField( required=True, error_messages={'required': '用户名不能为空'}, widget=widgets.TextInput(attrs={'class': 'form-control'})) password = fields.CharField(required=True, error_messages={ 'required': '密码不能为空', 'invalid': '密码格式错误' }) email = fields.EmailField(required=True, error_messages={ 'required': '邮箱不能为空', 'invalid': '邮箱格式错误' }) phone = fields.IntegerField(required=True, error_messages={'required': '电话不能为空'}) sl_id = fields.MultipleChoiceField(choices=[], widget=widgets.SelectMultiple()) def __init__(self, *args, **kwargs): super(UserForm, self).__init__(*args, **kwargs) self.fields['sl_id'].choices = models.Service_Line.objects.values_list( 'id', 'service_line_name')
class ClaimForm(forms.Form): unclaimed_packages = fields.MultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={'class': 'package-list-item'} ), choices=get_choices(), ) pin = fields.IntegerField(widget=forms.PasswordInput)
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')