Ticket #3297: 4490.2.patch

File 4490.2.patch, 5.0 KB (added by Øyvind Saltvik <oyvind.saltvik@…>, 18 years ago)

required validation + formfield_save_file

  • django/db/models/fields/__init__.py

     
    652652            else:
    653653                func(new_data[upload_field_name]["filename"], new_data[upload_field_name]["content"])
    654654
     655    def formfield_save_file(self, field_name, new_data, new_object):
     656        func = getattr(new_object, 'save_%s_file' % self.name)
     657        func(new_data[field_name][0]["filename"], new_data[field_name][0]["content"])
     658
    655659    def get_directory_name(self):
    656660        return os.path.normpath(datetime.datetime.now().strftime(self.upload_to))
    657661
     
    660664        f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename)))
    661665        return os.path.normpath(f)
    662666
     667    def formfield(self, **kwargs):
     668        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'widget':forms.FileInput}
     669        defaults.update(kwargs)
     670        return forms.FileField(**defaults)
     671
    663672class FilePathField(Field):
    664673    def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs):
    665674        self.path, self.match, self.recursive = path, match, recursive
  • django/newforms/models.py

     
    1313
    1414    This method is created for any form_for_model Form.
    1515    """
     16    from django.db import models
    1617    if self.errors:
    1718        raise ValueError("The %s could not be created because the data didn't validate." % self._model._meta.object_name)
    1819    return save_instance(self, self._model(), commit)
     
    3334    for f in opts.fields:
    3435        if isinstance(f, models.AutoField):
    3536            continue
     37        if isinstance(f,models.FileField):
     38            continue
    3639        setattr(instance, f.attname, clean_data[f.name])
    3740    if commit:
    3841        instance.save()
    3942        for f in opts.many_to_many:
    4043            setattr(instance, f.attname, clean_data[f.name])
     44       
     45        for f in opts.fields:
     46            if isinstance(f, models.FileField):
     47                f.formfield_save_file(f.name, clean_data, instance)
    4148    # GOTCHA: If many-to-many data is given and commit=False, the many-to-many
    4249    # data will be lost. This happens because a many-to-many options cannot be
    4350    # set on an object until after it's saved. Maybe we should raise an
  • django/newforms/fields.py

     
    1010import time
    1111
    1212__all__ = (
    13     'Field', 'CharField', 'IntegerField',
     13    'Field', 'CharField', 'FileField', 'IntegerField',
    1414    'DEFAULT_DATE_INPUT_FORMATS', 'DateField',
    1515    'DEFAULT_TIME_INPUT_FORMATS', 'TimeField',
    1616    'DEFAULT_DATETIME_INPUT_FORMATS', 'DateTimeField',
     
    107107        if self.max_length is not None and isinstance(widget, (TextInput, PasswordInput)):
    108108            return {'maxlength': str(self.max_length)}
    109109
     110class FileField(Field):
     111    def __init__(self,required=True,widget=None,label=None,initial=None):
     112        super(FileField,self).__init__(required,widget,label,initial)
     113   
     114    def clean(self, value):
     115        super(FileField,self).clean(value)
     116        if self.required:
     117            if value[0]:
     118                if not len(value[0]['content'])>0:
     119                    raise ValidationError(gettext(u'This field is required'))
     120            else:
     121                if not value[1]:
     122                    raise ValidationError(gettext(u'This field is required'))
     123        return value
     124
    110125class IntegerField(Field):
    111126    def __init__(self, max_value=None, min_value=None, *args, **kwargs):
    112127        self.max_value, self.min_value = max_value, min_value
  • django/newforms/widgets.py

     
    107107
    108108class FileInput(Input):
    109109    input_type = 'file'
     110   
     111    def render(self,name,value,attrs=None,choices=()):
     112        if value is None: value = ''
     113        file_attrs = self.build_attrs(attrs, type='file',name=name+'_file')
     114        final_attrs = self.build_attrs(attrs, type='hidden', name=name)
     115        if value != '': final_attrs['value'] = smart_unicode(value) # only add the value attribute if a value is non-empty
     116       
     117        if value != '':
     118            currently = u'Currently: %s<br/>Change: ' % smart_unicode(value)
     119        else:
     120            currently = u''
     121       
     122        return u'%s<input %s /> <input%s />' % (currently,flatatt(file_attrs),flatatt(final_attrs))
     123   
     124    def value_from_datadict(self,data,name):
     125        return [data.get(name+'_file',None),data.get(name,None)]
    110126
    111127class Textarea(Widget):
    112128    def render(self, name, value, attrs=None):
Back to Top