Django形成DateTimeInput小部件 - 如何指定最大日期?

时间:2017-01-03 16:08:56

标签: python django forms date restrictions

我的Django项目中显示了一个表单,其中一个表单字段是DateTimeInput窗口小部件,定义为:

    presentation_date = mDateTimeField(required=False, label="Presentation date", widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M')) 

此小部件目前显示去年年初至今年年底之间的所有日期(2016年1月1日至2017年3月31日)。然而,在去年年底,这引起了一些问题,因为这意味着用户无法选择今年年初的日期。我想要做的是将小部件中可供选择的日期范围扩展一年(即新范围将是01/01 / 2016-31 / 12/201)。

我知道可以使用表单验证来执行此操作(例如,通过编写clean_presentation_date()等视图并在该视图中执行验证,但这不会解决问题我&# 39; m当前,2016年1月1日之前或2017年12月31日之后的日期(显示在用户选择表单中字段时显示的datetimepicker日历中)是& #39;灰色'并且无法选择它们。这正是我想要的功能,但我只想更改执行日期的值,以便至少整个下一个日历年总是可以选择的。

我搜索了maxDate& minDate文件中forms.py个变量,其中定义了包含此字段的表单,但无法找到任何类似于限制哪些日期可供选择的内容,哪些是不可选择的。

显示带有此表单的网页的view定义为:

def concept(request, project_id):
    project = Project.objects.prefetch_related('budget_versions').get(id=project_id)
    deposit = Deposit.objects.get_or_create(project=project)[0]
    presentations = project.budget_versions.select_related('meeting').prefetch_related('budget_items', 'cci_items', 'presenters').filter(version_number__isnull=False).annotate(vn=F('version_number') * -1).order_by('presentation_date', 'created', '-vn')
    end_details = EndDetails.objects.get_or_create(project=project)[0]
    presentation_formset = BudgetPresentationFormset(prefix="presentations", instance=project, queryset=presentations)
    drawing_formset = DrawingUploadFormset(prefix="drawings", queryset=Drawing.objects.filter(budget__in=presentations).order_by('budget__presentation_date', 'budget__created'))

    context = {
        'project': project,
        'presentations': presentations,
        'presentation_formset': presentation_formset,
        'drawing_formset': drawing_formset,
        'deposit_form': DepositInfoForm(instance=deposit),
        'ended_form': EndDetailsForm(instance=end_details),
        'budget_notes_form': BudgetNotesForm(instance=project.budget_overview),
    }

我看到的form特定presentationsforms.py中定义的class FirstPresentationForm(ValidatedForm): """ UNUSED """ who_presenting = forms.CharField() details = forms.CharField(required=False, label='Original option costed') presentation_date = mDateTimeField(required=False, label="Presentation date", widget=forms.DateTimeInput(format='%d/%m/%Y %H:%M')) #ERF(19/12/2016 @ 1210) Remove 'datetimepicker' from field..., attrs=({'class':'datetimepicker'}))) class Meta: model = Budget fields = ('presentation_date','who_presenting','details') def __init__(self, *args, **kwargs): instance = kwargs.get('instance', {}) project = instance.project who_presenting = [pe.employee.id for pe in project.assigned.select_related('employee').filter(role=Role.P)] #Make into an array with two employee IDs, or None. If two results were found, they will already be in the right format if len(who_presenting)==1: who_presenting.append(None) elif not who_presenting: who_presenting = None if instance.presentation_date: pres_meeting, created = Meeting.objects.get_or_create(project=project, purpose='6') self.pres_meeting_id = pres_meeting.id self.pres_meeting_creator = pres_meeting.event_creator or '' if created: pres_meeting.date = instance.presentation_date pres_meeting.save() initial = kwargs.get('initial', {}) initial={ 'who_presenting': who_presenting, } kwargs['initial'] = initial super(FirstPresentationForm, self).__init__(*args, **kwargs) self.fields['who_presenting'] = AutoFlexiSelect(model='e', required=False, choices=get_choices('DESIGN_EMPLOYEE_CHOICES'), current_id=who_presenting, label="Who is presenting") self.fields['presentation_date'].widget.attrs.update({'data-meeting-id': getattr(self,'pres_meeting_id', ''), 'data-meeting-creator': getattr(self,'pres_meeting_creator', '')}) def save(self, commit=True): project = self.instance.project data = self.cleaned_data try: ProjectEmployee.objects.filter(project=project, role=Role.P).delete() #Delete current records, if any, to prevent build up on editing this field except ObjectDoesNotExist: pass if data['who_presenting']: designers = data['who_presenting'] # Get the ids from the form field (received as a string) designers = [re.sub('\D+', '', s) for s in designers.split(',')] who_presenting_1 = Employee.objects.get(id=designers[0]) who_presenting_2 = designers[1] #If only one employee in selected choice, this will be None if who_presenting_2: who_presenting_2 = Employee.objects.get(id=designers[1]) #If two employees in selected choice, sets the second one pe = ProjectEmployee(project=project, employee=who_presenting_1, role=Role.P) pe.save() if who_presenting_2: #If a second designer, delete as well pe = ProjectEmployee(project=project, employee=who_presenting_2, role=Role.P) pe.save() if 'presentation_date' in self.changed_data: from events.models import refresh_group_cache print '************' pres_meeting = Meeting.objects.get(project=project, purpose='6') self.instance.meeting = pres_meeting self.instance.save() print 'Updating date', data['presentation_date'], pres_meeting.id pres_meeting.date = data['presentation_date'] pres_meeting.save() refresh_group_cache(pres_meeting.event_creator.calendar_id, pres_meeting.date.year, pres_meeting.date.month, pres_meeting.event_id, pres_meeting) return super(FirstPresentationForm, self).save(commit=commit)

max_date

我尝试传递/设置presentation_date作为widget变量的属性,但它似乎没有这个名称的属性/属性......

如何指定特定日期作为此maxDate mDateTimeField,以便用户可以选择截至明年12月的日期,而不是直到12月今年?

修改

使用widget的{​​{1}}也在forms.py中定义,其中包含:

class mDateTimeField(forms.DateTimeField):
    def __init__(self, *args, **kwargs):
        kwargs.setdefault('input_formats', DATE_INPUT_FORMATS)
        super(mDateTimeField, self).__init__(*args, **kwargs)

1 个答案:

答案 0 :(得分:0)

这可以帮助您:

widgets = {
    'start_date': forms.DateInput(attrs={
        'class':'datepicker', 'data-min': YOUR_MIN_DATE, 
        'data-max': YOUR_MAX_DATE}),
}

<强>用法:

minDate: $(this).data('min'),
maxDate: $(this).data('max'),