Django窗体分成两个下拉(选择)

zomnis 发布于 2019-03-09 django 最后更新 2019-03-09 14:33 0 浏览

在我的表单中,我有expiry_date ....

expiry_date = forms.DateField()
到期日必须采用MMYY格式,即2013年12月的1213年。不应包含/或字符。 但是这对于最终用户来说在表单中看起来有点不合适。那么,是否有可能在Django中添加两个选择框1,一个月,一年,然后以某种方式将它们放回到一起,以便在post之前再次创建expiry_date? 即我希望我的用户在月份和年份查看下拉菜单,然后选择该下拉菜单。 这是我迄今为止....
CARD_CHOICES = [
    ('VISA', 'VISA'),
    ('MC', 'MasterCard'),
    ('DELTA', 'DELTA'),
    ('MAESTRO', 'Maestro'),
    ('UKE', 'Visa Electron'),
    ]
DATE_INPUT_FORMATS = ('MMYY',)
class OrderForm(forms.Form):
    """
    Order Form used to collect data ready for processing.
    """
    amount = forms.FloatField()
    expiry_date = forms.DateField(input_formats=DATE_INPUT_FORMATS)
    CSV = forms.CharField(max_length=3)
    card_type = forms.TypedChoiceField(choices=CARD_CHOICES, initial='VISA')
已邀请:

dmodi

赞同来自:

你基本上需要一个MultiValueField 以下是来自django-creditcard app的示例实现

class ExpiryDateField(forms.MultiValueField):
    """
    Form field that validates credit card expiry dates.
    """
default_error_messages = {
        'invalid_month': _(u'Please enter a valid month.'),
        'invalid_year': _(u'Please enter a valid year.'),
        'date_passed': _(u'This expiry date has passed.'),
    }
def __init__(self, *args, **kwargs):
        today = date.today()
        error_messages = self.default_error_messages.copy()
        if 'error_messages' in kwargs:
            error_messages.update(kwargs['error_messages'])
        if 'initial' not in kwargs:
            # Set default expiry date based on current month and year
            kwargs['initial'] = today
        months = [(x, '%02d (%s)' % (x, date(2000, x, 1).strftime(MONTH_FORMAT))) for x in xrange(1, 13)]
        years = [(x, x) for x in xrange(today.year, today.year + 15)]
        fields = (
            forms.ChoiceField(choices=months, error_messages={'invalid': error_messages['invalid_month']}),
            forms.ChoiceField(choices=years, error_messages={'invalid': error_messages['invalid_year']}),
        )
        super(ExpiryDateField, self).__init__(fields, *args, **kwargs)
        self.widget = ExpiryDateWidget(widgets=[fields[0].widget, fields[1].widget])
def clean(self, value):
        expiry_date = super(ExpiryDateField, self).clean(value)
        if date.today() > expiry_date:
            raise forms.ValidationError(self.error_messages['date_passed'])
        return expiry_date
def compress(self, data_list):
        if data_list:
            try:
                month = int(data_list[0])
            except (ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_month'])
            try:
                year = int(data_list[1])
            except (ValueError, TypeError):
                raise forms.ValidationError(self.error_messages['invalid_year'])
            try:
                day = monthrange(year, month)[1] # last day of the month
            except IllegalMonthError:
                raise forms.ValidationError(self.error_messages['invalid_month'])
            except ValueError:
                raise forms.ValidationError(self.error_messages['invalid_year'])
            return date(year, month, day)
        return None