def razzia_wizard(request): if request.method == 'POST': return redirect( reverse("razzia_view") + "?start={0}-{1}-{2}&end={3}-{4}-{5}&products={6}&username=&razzia_title={7}" .format( int(request.POST['start_year']), int(request.POST['start_month']), int( request.POST['start_day']), int(request.POST['end_year']), int(request.POST['end_month']), int(request.POST['end_day']), request.POST.get('products'), request.POST.get('razzia_title')) ) suggested_start_date = datetime.datetime.now() - datetime.timedelta( days=-180) suggested_end_date = datetime.datetime.now() start_date_picker = fields.DateField(widget=extras.SelectDateWidget( years=[x for x in range(2000, datetime.datetime.now().year + 1)])) end_date_picker = fields.DateField(widget=extras.SelectDateWidget( years=[x for x in range(2000, datetime.datetime.now().year + 1)])) return render( request, 'admin/stregsystem/razzia/wizard.html', { 'start_date_picker': start_date_picker.widget.render("start", suggested_start_date), 'end_date_picker': end_date_picker.widget.render("end", suggested_end_date) }, )
class SalesAchievementForm(Form): """电销业绩Form""" start_time = fields.DateField(widget=widgets.TextInput( attrs={ "class": "datepicker form-control", "id": "start_time", "placeholder": "起始日期" }), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" }) end_time = fields.DateField(widget=widgets.TextInput( attrs={ "class": "datepicker form-control", "id": "end_time", "placeholder": "终止日期" }), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" }) kefu_id = fields.CharField( widget=widgets.TextInput(attrs={ "class": "form-control", "id": "kefu_id", "placeholder": "客服ID" }), error_messages={ "required": "客服ID不能为空!", "invalid": "请输入正确的客服ID!" })
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
def __init__(self, *args, **kwargs): flds = (fields.DateField(label='Date from'), fields.DateField(label='Date to') ) super(ReservationRange, self).__init__( fields = flds, *args, **kwargs ) self.widget = ReservationRangeWidget(widgets = [flds[0].widget, flds[1].widget])
class ThisForm(forms.Form): start_date = fields.DateField(initial='2012-03-01') end_date = fields.DateField(initial='2012-03-31') task = fields.ChoiceField(widget=forms.RadioSelect, choices=( ('imp', 'Import logs'), ('geo', 'Update Geo & ASN'), ('pars', 'Parse, analyze and store verdicts'), ))
class PlanningRequestForm(ModelForm): class Meta: model = PlanningRequest exclude = [ "state", "budget_feedback", "decoration_descr", "parties_descr", "drinks_descr", "food_descr", "media_descr" ] client = forms.ModelChoiceField(queryset=Client.objects.all(), required=False) from_date = fields.DateField(widget=SelectDateWidget()) to_date = fields.DateField(widget=SelectDateWidget())
class RegisterAuth(forms.Form): Name = fields.CharField(max_length=12, min_length=2, error_messages={'required': '昵称不能为空', 'max_length': '昵称长度不能大于12', 'min_length': '昵称长度不能小于2'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'name': 'Name', 'placeholder': 'Tony-stark'})) Email = fields.EmailField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'}, widget=widgets.EmailInput(attrs={'class': 'form-control', 'name': 'Email', 'placeholder': '*****@*****.**'})) Password = fields.CharField(max_length=12, min_length=6, error_messages={'required': '密码不能为空', 'max_length': '密码长度不能大于12', 'min_length': '密码长度不能小于6'}, widget=widgets.PasswordInput(attrs={'class': 'form-control', 'name': 'Password', 'placeholder': 'Password'})) Birthday = fields.DateField(error_messages={'required': '生日不能为空', 'invalid': '生日格式错误'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'name': 'Birthday', 'placeholder': '1995-09-20'})) PhoneNum = fields.CharField(max_length=12, min_length=8, error_messages={'required': '手机号码不能为空', 'max_length': '手机号码长度不能大于12', 'min_length': '手机号码长度不能小于6'}, widget=widgets.TextInput(attrs={'class': 'form-control', 'name': 'PhoneNum', 'placeholder': '18102588262'})) Hobby = fields.CharField(max_length=12, error_messages={'required': '爱好不能为空', 'max_length': '爱好长度不能大于12', }, widget=widgets.TextInput(attrs={'class': 'form-control', 'name': 'Hobby', 'placeholder': '写代码、装B'}))
class StudentEditForm(forms.ModelForm): gender = Ffields.ChoiceField(required=True, choices=((1, '男'), (2, '女')), widget=Fwidgets.RadioSelect()) birthday = Ffields.DateField( required=False, widget=DateTimePickerInput(attrs={ 'type': 'date', 'style': 'width: 600px' })) class Meta: model = stumodels.StudentInfo fields = ("last_name", 'first_name', 'full_name', "gender", "birthday", 'period', 'school', 'period', 'age', 'day_age', 'constellation', 'chinese_zodiac', 'school') widgets = { "last_name": Fwidgets.TextInput(attrs={ 'class': 'form-control', 'style': 'width: 600px' }), "first_name": Fwidgets.TextInput(attrs={ 'class': 'form-control', 'style': 'width: 600px' }), "school": Ffields.Select(attrs={ 'class': 'form-control', 'style': 'width: 600px' }) }
class CreateCabinetForms(forms.Form): # idc = models.ForeignKey('IDCInfo', verbose_name='所属机房') # number = models.CharField(max_length=64, verbose_name='机柜编号') # customer = models.ForeignKey('Customer', verbose_name='所属客户') # open_date = models.DateField(verbose_name='机柜开通日期', blank=True, null=True, default=datetime.datetime.now().date()) idc = fields.CharField(required=True) number = fields.CharField( required=True, label= '<label for="id_number" class="col-sm-2 control-label">机柜编号</label>', widget=forms.TextInput(attrs={ 'placeholder': "机柜编号", 'class': 'form-control' })) customer = fields.CharField( required=True, widget=forms.Select(attrs={'class': "form-control"}), label= '<label for="id_customer" class="col-sm-2 control-label">客户</label>') open_date = fields.DateField(required=True, widget=widgets.DateInput) def __init__(self, *args, **kwargs): super(CreateCabinetForms, self).__init__(*args, **kwargs) # self.customer.widget = models.Customer.objects.values_list('id', 'name') self.fields[ 'customer'].widget.choices = models.Customer.objects.values_list( 'id', 'name')
class ActivityForm(Form): """党日活动Form""" title = fields.CharField(required=False, label='活动主题', max_length=128, error_messages={'required': '活动主题不能为空'}, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入活动主题" })) time = fields.DateField(required=False, label='活动时间', error_messages={'required': '活动日期不能为空!'}, widget=forms.TextInput(attrs={ 'class': 'form-control', 'type': 'date' })) place = fields.CharField(required=False, label='活动地点', max_length=64, error_messages={'required': '活动地点不能为空'}, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': "请输入活动地点" })) content = UEditorField( u'活动内容', required=False, height=450, toolbars="full", error_messages={'required': '活动内容不能为空'}, )
def __init__(self, *args, **kwargs): """ Have to pass a list of field types to the constructor, else we won't get any data to our compress method. """ all_fields = (fields.DateField(), fields.TimeField()) super(SplitDateTimeField, self).__init__(all_fields, *args, **kwargs)
class EditProfilePage(UserEditForm): def __init__(self, *args, **kwargs): super(EditProfilePage, self).__init__(*args, **kwargs) for field in self.Meta.fields: self.fields[field].required = False self.fields.pop('username') self.fields.pop('is_superuser') self.fields.pop('email') birthday = fields.DateField( required=False, widget=forms.widgets.DateInput(attrs={'type': 'date'})) subunions = forms.ModelChoiceField(queryset=Subunions.objects.all(), required=False, widget=forms.Select, empty_label=None) class Meta: model = User fields = ('email', 'username', 'first_name', 'last_name', 'birthday', 'subunions', 'password1', 'password2') def clean_birthday(self): birthday = self.cleaned_data.get("birthday") if birthday is not None: if birthday < VALID_BIRTHDAY_FROM or birthday > VALID_BIRTHDAY_TO: raise forms.ValidationError("Please enter a valid birthday.") return birthday
class CreateForm(Form): title_create = fields.CharField( label='Title', required=True, max_length=128, widget=widgets.Textarea(attrs={'class': 'title_create'})) estimate_create = fields.DateField( label='Estimate', required=True, input_formats=['%d-%m-%Y'], widget=widgets.DateInput(attrs={'class': 'estimate_create'})) def get_data_to_create(self): title = self.data.get("title_create") date = self.data.get("estimate_create") try: date = datetime.strptime(date, "%d-%m-%Y").date() except ValueError: raise ValueError( "Incorrect data! Date should have format 'dd-mm-yyyy'") if date <= datetime.now().date(): raise ValueError("Incorrect data! Date can't be less than today") return (title, date)
def __init__(self, input_formats=None, *args, **kwargs): errors = self.default_error_messages.copy() if 'error_messages' in kwargs: errors.update(kwargs['error_messages']) localize = kwargs.get('localize', False) fields_ = ( fields.DateField(input_formats=input_formats, error_messages={'invalid': errors['invalid']}, localize=localize), fields.DateField(input_formats=input_formats, error_messages={'invalid': errors['invalid']}, localize=localize), ) super(DateRangeField, self).__init__(fields_, *args, **kwargs)
class MonthlyForm(Form): """月度数据所需FORM""" qdate = fields.DateField(widget=widgets.TextInput( attrs={"class": "datepicker right search form-control"}), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" })
class ReportForm(forms.Form): REPORT_CHOICES = ( ('1', 'highestratedroom'), ('2', 'fivebestcustomers'), ('3', 'highestratedbreakfast'), ('4', 'highestratedservice'), ) report_type = fields.ChoiceField(choices=REPORT_CHOICES, required=True) start_date = fields.DateField(initial=datetime.date.today) end_date = fields.DateField(initial=datetime.date.today) def __init__(self, *args, **kwargs): super(ReportForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' })
class EventForm(forms.Form): name = fields.CharField(max_length=150, label='display name') start_date = fields.DateField(widget=AdminDateWidget) end_date = fields.DateField(widget=AdminDateWidget) def _get_media(self): # The "core.js" file is required by the Admin Date widget, yet for # some reason, isn't included in the widgets media definition. # We override "_get_media" because core.js needs to appear BEFORE # the widget's JS files, and the default order puts the form's # media AFTER that of its fields. media = widgets.Media( js=('%sjs/core.js' % settings.ADMIN_MEDIA_PREFIX,) ) media += super(EventForm, self)._get_media() return media media = property(_get_media)
class ProfileForm(ModelForm): dob = fields.DateField(widget=forms.widgets.DateInput( attrs={'type': 'date'})) description = forms.CharField(widget=forms.Textarea) class Meta: model = Profile exclude = ['user', 'address', 'created_date', 'updated_date']
class DateRangeFilterForm(FilterFormBase): start_date = fields.DateField(required=False) end_date = fields.DateField(required=False, initial=str(datetime.today().date())) filter_attribute_name = None def __new__(cls, *args, **kwargs): class_obj = super(DateRangeFilterForm, cls).__new__(cls) assert class_obj.filter_attribute_name is not None return class_obj def clean_start_date(self): start_date = self.cleaned_data['start_date'] if start_date: if start_date > datetime.today().date(): raise ValidationError('Start date can not be later than today', code='out-of-range') return start_date def clean_end_date(self): start_date = self.cleaned_data['start_date'] end_date = self.cleaned_data['end_date'] if start_date and end_date: if end_date < start_date: raise ValidationError('End date can not preceed start date', code='incorrect-order') return end_date def filter(self, data): """ Filters the filtered attribute on the given range """ start_date = self.cleaned_data['start_date'] end_date = self.cleaned_data['end_date'] data = super(DateRangeFilterForm, self).filter(data) if start_date: filter_name = f'{self.filter_attribute_name}__gte' data = data.filter(**{ filter_name: start_date }) if end_date: filter_name = f'{self.filter_attribute_name}__lte' data = data.filter(**{ filter_name: end_date }) return data
class CrimeSearchForm(IDForm): first_name = fields.CharField(required=False, max_length=42) last_name = fields.CharField(required=False, max_length=42) birthdate = fields.DateField(required=False, widget=widgets.DateInput) sid = forms.IntegerField(required=False) search_by_field = fields.MultipleChoiceField( required=False, widget=widgets.CheckboxSelectMultiple, choices=[("First Name", "first_name"), ("Last Name", "last_name"), ("Birth date", "birthdate"), ("SID number", "sid")])
class CadastroUsuarioForm(forms.Form): SEXO_CHOICES = ((u'F', u'Feminino'), (u'M', u'Masculino')) nome = forms.CharField(max_length=100, label='Nome') cpf = forms.CharField(max_length=11, label='CPF') data_nasc = fields.DateField(widget=forms.widgets.DateInput( attrs={'type': 'date'})) sexo = forms.ChoiceField(choices=SEXO_CHOICES, label='Sexo') telefone = forms.CharField(max_length=11, label='Telefone') endereco = forms.CharField(max_length=100, label='Endereço') email = forms.EmailField(max_length=100, label='E-mail') pass_user = forms.CharField(widget=forms.PasswordInput, label='Senha')
class PostForm(forms.Form): title = fields.CharField(max_length=255, required=True) description = fields.CharField(max_length=500, required=True) content = fields.TextInput() date = fields.DateField(required=True) def save(self, author): if self.is_valid(): post = Post(author_id=author.pk, **self.cleaned_data) post.full_clean() post.save()
class DailyForm(Form): """日报页面所属FORM""" qdate = fields.DateField(widget=widgets.TextInput( attrs={"class": "datepicker right search form-control"}), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" }) section = fields.ChoiceField(required=False, choices=[("8", 8), ("14", 14)], widget=widgets.Select())
class AssignmentForm(forms.ModelForm): beginnig = fields.DateField(widget=forms.DateInput( attrs={'class': 'date-picker'})) end = fields.DateField(widget=forms.DateInput( attrs={'class': 'date-picker'})) next = fields.CharField(widget=forms.HiddenInput()) class Meta: exclude = ['date'] model = Assignment def save(self, commit=True): dates = date_range_inclusive(self.cleaned_data['beginnig'], self.cleaned_data['end'], exclude_weekends=True) for date in dates: Assignment.objects.create( **{ 'date': date, 'person': self.cleaned_data['person'], 'project': self.cleaned_data['project'], })
class SmStForm(Form): """实名首投查询""" start_time = fields.DateField(widget=widgets.TextInput( attrs={ "class": "datepicker form-control", "id": "start_time", "placeholder": "起始日期" }), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" }) end_time = fields.DateField(widget=widgets.TextInput( attrs={ "class": "datepicker form-control", "id": "end_time", "placeholder": "终止日期" }), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" }) qudao_name = fields.CharField( widget=widgets.TextInput(attrs={ "class": "form-control", "id": "qudao-name", "placeholder": "请输入渠道名称" }), error_messages={ "required": "渠道名称不能为空!", }) data_type = fields.ChoiceField(choices=[("1", "实名"), ("2", "首投")], widget=widgets.Select()) def __init__(self, *args, **kwargs): super(SmStForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): from curia.widgets import * errors = self.default_error_messages.copy() if 'error_messages' in kwargs: errors.update(kwargs['error_messages']) fields = ( djfields.DateField( error_messages={'invalid': errors['invalid_date']}), djfields.TimeField( error_messages={'invalid': errors['invalid_time']}), ) self.widget = SplitDateTimeWidget2 super(SplitDateTimeField, self).__init__(fields, *args, **kwargs)
class TeacherEditModelForm(StarkModelForm): birthday = Ffields.DateField( required=False, label='生日', widget=Fwidgets.DateInput(attrs={ 'type': 'date', 'style': 'width: 600px' })) identity = form_models.ModelChoiceField( required=False, empty_label=None, label='职务', queryset=teamodels.Identity.objects.all(), widget=Fwidgets.RadioSelect()) course = form_models.ModelMultipleChoiceField( required=False, label='所带课程', queryset=scmodels.Course.objects.all(), widget=Fwidgets.CheckboxSelectMultiple()) gender = Ffields.ChoiceField(required=False, label='性别', choices=((1, '男'), (2, '女')), widget=Fwidgets.RadioSelect()) class Meta: model = teamodels.TeacherInfo fields = ('last_name', 'first_name', 'gender', 'birthday', 'telephone', 'wechat', 'school', 'identity', 'course') widgets = { "last_name": Fwidgets.TextInput(attrs={'style': 'width: 600px'}), "first_name": Fwidgets.TextInput(attrs={'style': 'width: 600px'}), 'wechat': Fwidgets.TextInput(attrs={'style': 'width: 600px'}), 'telephone': Fwidgets.TextInput(attrs={'style': 'width: 600px'}), 'school': Fwidgets.Select(attrs={'style': 'width: 600px'}), } error_messages = { "last_name": { "required": "请输入老师姓" }, "first_name": { "required": "请输入老师名" }, "gender": { "required": "请选择性别" }, } labels = { 'last_name': '老师姓(必填)', 'first_name': '老师名(必填)', }
def end_time(cls): field = fields.DateField( label="终止日期", widget=widgets.TextInput(attrs={ "class": "form-control date-picker", "id": "end_time", "value": datetime.strftime(datetime.now() - timedelta(1), "%Y-%m-%d"), "placeholder": "终止日期" }), error_messages={ "required": "日期不能为空!", "invalid": "请输入正确的日期格式!" } ) return field
class ChargesForm(Form): date = fields.DateField(label='date') value = fields.DecimalField(label='value') def clean(self): cleaned_data = super(ChargesForm, self).clean() date_charge = cleaned_data.get('date') value_charge = cleaned_data.get('value') today = date.today() if value_charge < 0: if date_charge > today: self.add_error('date', "Impossible to make a write-off") self.add_error('value', "Impossible to make a write-off") return cleaned_data
def test_nonfield_errors(form, request_factory): request = request_factory().get('some?__submit=siteform&some=hmm') frm = form( composer=Composer, some=fields.DateField(widget=fields.HiddenInput()) )(src='GET', request=request) frm.is_valid() frm.add_error(None, 'Errr1') frm.add_error(None, 'Errr2') form_html = f'{frm}' assert '<div ><div>Errr1</div>\n<div>Errr2</div>' in form_html assert 'Hidden field "some": Enter a valid date.' in form_html