Django

Code

Changeset 7021

Show
Ignore:
Timestamp:
01/17/08 12:03:21 (6 months ago)
Author:
jkocherhans
Message:

Fixed #6302. FileField? no longer requires a value if one already exists. Thanks Brian Rosner and Øyvind Saltvik.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/fields/__init__.py

    r6935 r7021  
    798798 
    799799    def save_form_data(self, instance, data): 
    800         if data: 
     800        from django.newforms.fields import UploadedFile 
     801        if data and isinstance(data, UploadedFile): 
    801802            getattr(instance, "save_%s_file" % self.name)(data.filename, data.content, save=False) 
    802803 
     
    805806        # If a file has been provided previously, then the form doesn't require 
    806807        # that a new file is provided this time. 
     808        # The code to mark the form field as not required is used by 
     809        # form_for_instance, but can probably be removed once form_for_instance 
     810        # is gone. ModelForm uses a different method to check for an existing file. 
    807811        if 'initial' in kwargs: 
    808812            defaults['required'] = False 
  • django/trunk/django/newforms/fields.py

    r6875 r7021  
    438438        super(FileField, self).__init__(*args, **kwargs) 
    439439 
    440     def clean(self, data): 
    441         super(FileField, self).clean(data) 
     440    def clean(self, data, initial=None): 
     441        super(FileField, self).clean(initial or data) 
    442442        if not self.required and data in EMPTY_VALUES: 
    443443            return None 
     444        elif not data and initial: 
     445            return initial 
    444446        try: 
    445447            f = UploadedFile(data['filename'], data['content']) 
     
    457459    } 
    458460 
    459     def clean(self, data): 
     461    def clean(self, data, initial=None): 
    460462        """ 
    461463        Checks that the file-upload field data contains a valid image (GIF, JPG, 
    462464        PNG, possibly others -- whatever the Python Imaging Library supports). 
    463465        """ 
    464         f = super(ImageField, self).clean(data
     466        f = super(ImageField, self).clean(data, initial
    465467        if f is None: 
    466468            return None 
  • django/trunk/django/newforms/forms.py

    r6671 r7021  
    1010from django.utils.safestring import mark_safe 
    1111 
    12 from fields import Field 
     12from fields import Field, FileField 
    1313from widgets import TextInput, Textarea 
    1414from util import flatatt, ErrorDict, ErrorList, ValidationError 
     
    183183            value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) 
    184184            try: 
    185                 value = field.clean(value) 
     185                if isinstance(field, FileField): 
     186                    initial = self.initial.get(name, field.initial) 
     187                    value = field.clean(value, initial) 
     188                else: 
     189                    value = field.clean(value) 
    186190                self.cleaned_data[name] = value 
    187191                if hasattr(self, 'clean_%s' % name): 
  • django/trunk/tests/modeltests/model_forms/models.py

    r6917 r7021  
    77most of these tests should be rewritten. 
    88""" 
     9 
     10import os 
     11import tempfile 
    912 
    1013from django.db import models 
     
    5558    def __unicode__(self): 
    5659        return self.phone 
     60 
     61class TextFile(models.Model): 
     62    description = models.CharField(max_length=20) 
     63    file = models.FileField(upload_to=tempfile.gettempdir()) 
     64 
     65    def __unicode__(self): 
     66        return self.description 
    5767 
    5868__test__ = {'API_TESTS': """ 
     
    702712>>> f.cleaned_data 
    703713{'phone': u'312-555-1212', 'description': u'Assistance'} 
     714 
     715# FileField ################################################################### 
     716 
     717>>> class TextFileForm(ModelForm): 
     718...     class Meta: 
     719...         model = TextFile 
     720 
     721Test conditions when files is either not given or empty. 
     722 
     723>>> f = TextFileForm(data={'description': u'Assistance'}) 
     724>>> f.is_valid() 
     725False 
     726>>> f = TextFileForm(data={'description': u'Assistance'}, files={}) 
     727>>> f.is_valid() 
     728False 
     729 
     730Upload a file and ensure it all works as expected. 
     731 
     732>>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': {'filename': 'test1.txt', 'content': 'hello world'}}) 
     733>>> f.is_valid() 
     734True 
     735>>> type(f.cleaned_data['file']) 
     736<class 'django.newforms.fields.UploadedFile'> 
     737>>> instance = f.save() 
     738>>> instance.file 
     739u'.../test1.txt' 
     740 
     741Edit an instance that already has the file defined in the model. This will not 
     742save the file again, but leave it exactly as it is. 
     743 
     744>>> f = TextFileForm(data={'description': u'Assistance'}, instance=instance) 
     745>>> f.is_valid() 
     746True 
     747>>> f.cleaned_data['file'] 
     748u'.../test1.txt' 
     749>>> instance = f.save() 
     750>>> instance.file 
     751u'.../test1.txt' 
     752 
     753Delete the current file since this is not done by Django. 
     754 
     755>>> os.unlink(instance.get_file_filename()) 
     756 
     757Override the file by uploading a new one. 
     758 
     759>>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': {'filename': 'test2.txt', 'content': 'hello world'}}, instance=instance) 
     760>>> f.is_valid() 
     761True 
     762>>> instance = f.save() 
     763>>> instance.file 
     764u'.../test2.txt' 
     765 
     766>>> instance.delete() 
     767 
     768Test the non-required FileField 
     769 
     770>>> f = TextFileForm(data={'description': u'Assistance'}) 
     771>>> f.fields['file'].required = False 
     772>>> f.is_valid() 
     773True 
     774>>> instance = f.save() 
     775>>> instance.file 
     776'' 
     777 
     778>>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': {'filename': 'test3.txt', 'content': 'hello world'}}, instance=instance) 
     779>>> f.is_valid() 
     780True 
     781>>> instance = f.save() 
     782>>> instance.file 
     783u'.../test3.txt' 
     784>>> instance.delete() 
    704785"""} 
  • django/trunk/tests/regressiontests/forms/fields.py

    r6746 r7021  
    751751ValidationError: [u'This field is required.'] 
    752752 
    753 >>> f.clean(None) 
    754 Traceback (most recent call last): 
    755 ... 
    756 ValidationError: [u'This field is required.'] 
     753>>> f.clean('', '') 
     754Traceback (most recent call last): 
     755... 
     756ValidationError: [u'This field is required.'] 
     757 
     758>>> f.clean('', 'files/test1.pdf') 
     759'files/test1.pdf' 
     760 
     761>>> f.clean(None) 
     762Traceback (most recent call last): 
     763... 
     764ValidationError: [u'This field is required.'] 
     765 
     766>>> f.clean(None, '') 
     767Traceback (most recent call last): 
     768... 
     769ValidationError: [u'This field is required.'] 
     770 
     771>>> f.clean(None, 'files/test2.pdf') 
     772'files/test2.pdf' 
    757773 
    758774>>> f.clean({}) 
     
    761777ValidationError: [u'No file was submitted.'] 
    762778 
     779>>> f.clean({}, '') 
     780Traceback (most recent call last): 
     781... 
     782ValidationError: [u'No file was submitted.'] 
     783 
     784>>> f.clean({}, 'files/test3.pdf') 
     785'files/test3.pdf' 
     786 
    763787>>> f.clean('some content that is not a file') 
    764788Traceback (most recent call last): 
     
    766790ValidationError: [u'No file was submitted. Check the encoding type on the form.'] 
    767791 
    768 >>> f.clean({'filename': 'name', 'content':None}) 
     792>>> f.clean({'filename': 'name', 'content': None}) 
    769793Traceback (most recent call last): 
    770794... 
    771795ValidationError: [u'The submitted file is empty.'] 
    772796 
    773 >>> f.clean({'filename': 'name', 'content':''}) 
     797>>> f.clean({'filename': 'name', 'content': ''}) 
    774798Traceback (most recent call last): 
    775799... 
    776800ValidationError: [u'The submitted file is empty.'] 
    777801 
    778 >>> type(f.clean({'filename': 'name', 'content':'Some File Content'})) 
     802>>> type(f.clean({'filename': 'name', 'content': 'Some File Content'})) 
     803<class 'django.newforms.fields.UploadedFile'> 
     804 
     805>>> type(f.clean({'filename': 'name', 'content': 'Some File Content'}, 'files/test4.pdf')) 
    779806<class 'django.newforms.fields.UploadedFile'> 
    780807