Ticket #3297: 4490.patch

File 4490.patch, 4.7 KB (added by Øyvind Saltvik <oyvind.saltvik@…>, 12 years ago)

Checked against trunk, made file saving overridable in filefield as newforms_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 newforms_save_file(self, new_data, new_object):
     656        if new_data.get(self.name, False):
     657            func = getattr(new_object, 'save_%s_file' % self.name)
     658            func(new_data[self.name][0]["filename"], new_data[self.name][0]["content"])
     659
    655660    def get_directory_name(self):
    656661        return os.path.normpath(datetime.datetime.now().strftime(self.upload_to))
    657662
     
    660665        f = os.path.join(self.get_directory_name(), get_valid_filename(os.path.basename(filename)))
    661666        return os.path.normpath(f)
    662667
     668    def formfield(self, **kwargs):
     669        defaults = {'required': not self.blank, 'label': capfirst(self.verbose_name), 'widget':forms.FileInput}
     670        defaults.update(kwargs)
     671        return forms.FileField(**defaults)
     672
    663673class FilePathField(Field):
    664674    def __init__(self, verbose_name=None, name=None, path='', match=None, recursive=False, **kwargs):
    665675        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.newforms_save_file(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        return value
     117
    110118class IntegerField(Field):
    111119    def __init__(self, max_value=None, min_value=None, *args, **kwargs):
    112120        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