我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.forms.DateField()。
def test_create_unbound_form_field_types_1(self): form = PartyForm( schema_selectors=( {'name': None, 'selector': self.fixtures['org1'].pk}, {'name': 'project', 'value': self.fixtures['proj11'], 'selector': self.fixtures['proj11'].pk} ) ) assert form.attributes_field == 'attrs' assert 'name' in form.fields assert 'project' in form.fields assert 'attrs::dob' in form.fields assert isinstance(form.fields['attrs::dob'], forms.DateField) assert 'attrs::gender' in form.fields assert isinstance(form.fields['attrs::gender'], forms.CharField) assert 'attrs::education' in form.fields assert isinstance(form.fields['attrs::education'], forms.CharField) assert 'attrs::homeowner' in form.fields assert isinstance(form.fields['attrs::homeowner'], forms.BooleanField) assert len(form.fields) == 6
def __init__(self, verbose_name=None, name=None, auto_now=False, auto_now_add=False, **kwargs): self.auto_now, self.auto_now_add = auto_now, auto_now_add if auto_now or auto_now_add: kwargs['editable'] = False kwargs['blank'] = True super(DateField, self).__init__(verbose_name, name, **kwargs)
def deconstruct(self): name, path, args, kwargs = super(DateField, self).deconstruct() if self.auto_now: kwargs['auto_now'] = True if self.auto_now_add: kwargs['auto_now_add'] = True if self.auto_now or self.auto_now_add: del kwargs['editable'] del kwargs['blank'] return name, path, args, kwargs
def get_internal_type(self): return "DateField"
def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = datetime.date.today() setattr(model_instance, self.attname, value) return value else: return super(DateField, self).pre_save(model_instance, add)
def contribute_to_class(self, cls, name, **kwargs): super(DateField, self).contribute_to_class(cls, name, **kwargs) if not self.null: setattr(cls, 'get_next_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True)) setattr(cls, 'get_previous_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False))
def formfield(self, **kwargs): defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(DateField, self).formfield(**defaults)
def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super(DateTimeField, self).pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO # get_prep_lookup is inherited from DateField
def _get_form_fields(self): return OrderedDict(( (self.lookup_kwarg_gte, forms.DateField( label='', widget=AdminDateWidget(attrs={'placeholder': _('From date')}), localize=True, required=False )), (self.lookup_kwarg_lte, forms.DateField( label='', widget=AdminDateWidget(attrs={'placeholder': _('To date')}), localize=True, required=False )), ))
def test_create_bound_form_field_types_1(self): party = self.fixtures['party111'] form = PartyForm(instance=party) assert form.attributes_field == 'attrs' assert 'name' in form.fields assert 'project' in form.fields assert 'attrs::dob' in form.fields assert isinstance(form.fields['attrs::dob'], forms.DateField) assert 'attrs::gender' in form.fields assert isinstance(form.fields['attrs::gender'], forms.CharField) assert 'attrs::education' in form.fields assert isinstance(form.fields['attrs::education'], forms.CharField) assert 'attrs::homeowner' in form.fields assert isinstance(form.fields['attrs::homeowner'], forms.BooleanField) assert len(form.fields) == 6
def angular_model(model, angular_model_name, extra_params={}): """ Returns javascript that preprocesses obj before attaching it to window where angular controller can grab it """ ret = "<script>\n" if model is None: ret += "window.%s = {};\n" % (angular_model_name) else: # cast foreign key and m2m fields to be strings json_ret = model.to_json() model_dict = json.loads(json_ret) fk_fields = model.get_foreign_key_fields() m2m_fields = model.get_many_to_many_fields() for field, val in model_dict["fields"].iteritems(): if field in fk_fields: model_dict["fields"][field] = str(val) if field in m2m_fields: model_dict["fields"][field] = map(str, val) ret += "window.%s = %s;\n" % (angular_model_name, json.dumps(model_dict, sort_keys=True)) # adds converter for datetime fields for field in model.READABLE_ATTRS(type_filter=models.DateField): # DateTimeFields are instances of DateFields ret += ("window.%s.fields.%s = new Date(window.%s.fields.%s);\n" % (angular_model_name, field, angular_model_name, field)) # date_fields = model.WRITEABLE_ATTRS(type_filter=models.DateField, type_exclude=models.DateTimeField) # date_fields = json.dumps(date_fields) # ret += "window.%s.date_fields = %s" % (angular_model_name, date_fields) ret += "</script>\n" return mark_safe(ret)
def angular_input_field(form_field, angular_model_name, extra_params={}): try: form_field_value = form_field.value form_field.value = lambda: None attrs = {"ng-model": "%s.fields.%s" % (angular_model_name, form_field.name), "class": "form-control"} if form_field.field.required: attrs["required"] = "true" if isinstance(form_field.field, DateTimeField): separator = extra_params.pop("silica_datetime_separator", "") widget1 = _get_datepicker(form_field, attrs, extra_params) attrs["type"] = "time" attrs.update(extra_params) widget2 = form_field.as_widget(attrs=attrs) return format_html(widget1 + separator + widget2) if isinstance(form_field.field, DateField): return format_html(_get_datepicker(form_field, attrs, extra_params)) if isinstance(form_field.field, ModelChoiceField): pass #return format_html(_get_datepicker(form_field, attrs, extra_params)) if isinstance(form_field.field, ModelMultipleChoiceField): pass #return format_html(_get_datepicker(form_field, attrs, extra_params)) attrs.update(extra_params) return format_html(form_field.as_widget(attrs=attrs)) finally: form_field.value = form_field_value
def test_fields(self): """ This tests that all fields were added to the form with the correct types """ form_class = self.fb.get_form_class() field_names = form_class.base_fields.keys() # All fields are present in form self.assertIn('your-name', field_names) self.assertIn('your-biography', field_names) self.assertIn('your-birthday', field_names) self.assertIn('your-birthtime', field_names) self.assertIn('your-email', field_names) self.assertIn('your-homepage', field_names) self.assertIn('your-favourite-number', field_names) self.assertIn('your-favourite-python-ides', field_names) self.assertIn('your-favourite-python-ide', field_names) self.assertIn('your-choices', field_names) self.assertIn('i-agree-to-the-terms-of-use', field_names) # All fields have proper type self.assertIsInstance(form_class.base_fields['your-name'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-biography'], forms.CharField) self.assertIsInstance(form_class.base_fields['your-birthday'], forms.DateField) self.assertIsInstance(form_class.base_fields['your-birthtime'], forms.DateTimeField) self.assertIsInstance(form_class.base_fields['your-email'], forms.EmailField) self.assertIsInstance(form_class.base_fields['your-homepage'], forms.URLField) self.assertIsInstance(form_class.base_fields['your-favourite-number'], forms.DecimalField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ides'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'], forms.ChoiceField) self.assertIsInstance(form_class.base_fields['your-choices'], forms.MultipleChoiceField) self.assertIsInstance(form_class.base_fields['i-agree-to-the-terms-of-use'], forms.BooleanField) # Some fields have non-default widgets self.assertIsInstance(form_class.base_fields['your-biography'].widget, forms.Textarea) self.assertIsInstance(form_class.base_fields['your-favourite-python-ide'].widget, forms.RadioSelect) self.assertIsInstance(form_class.base_fields['your-choices'].widget, forms.CheckboxSelectMultiple)
def __init__(self, input_formats=None, format=None, *args, **kwargs): self.input_formats = self.input_formats if input_formats is None else input_formats self.format = self.format if format is None else format super(DateField, self).__init__(*args, **kwargs)
def test_should_date_convert_string(): assert_conversion(forms.DateField, graphene.String)
def setUp(self): class TestForm(forms.Form): char = forms.CharField(max_length=255) hidden = forms.CharField(max_length=255, widget=forms.HiddenInput()) date = forms.DateField(widget=AdminDateWidget()) datetime = forms.DateTimeField(widget=AdminSplitDateTime()) self.form = TestForm({ 'char': 'hi there', 'hidden': 'hidden text', 'date': '20140111', })
def contribute_to_class(self, cls, name, **kwargs): super(DateField, self).contribute_to_class(cls, name, **kwargs) if not self.null: setattr( cls, 'get_next_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=True) ) setattr( cls, 'get_previous_by_%s' % self.name, curry(cls._get_next_or_previous_by_FIELD, field=self, is_next=False) )
def pre_save(self, model_instance, add): if self.auto_now or (self.auto_now_add and add): value = timezone.now() setattr(model_instance, self.attname, value) return value else: return super(DateTimeField, self).pre_save(model_instance, add) # contribute_to_class is inherited from DateField, it registers # get_next_by_FOO and get_prev_by_FOO
def get_form_field(self, **kwargs): """Return a Django form field appropriate for a date property. This defaults to a DateField instance, except if auto_now or auto_now_add is set, in which case None is returned, as such 'auto' fields should not be rendered as part of the form. """ if self.auto_now or self.auto_now_add: return None defaults = {'form_class': forms.DateField} defaults.update(kwargs) return super(DateProperty, self).get_form_field(**defaults)