Example #1
0
class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)

    # Call this 'picture' so it gets copied from the form to the in-memory model
    # It will not be the "bytes", it will be the "InMemoryUploadedFile"
    # because we need to pull out things like content_type
    picture = forms.FileField(required=False, label='File to Upload <= '+max_upload_limit_text)
    upload_field_name = 'picture'

    class Meta:
        model = Ad
        fields = ['title', 'text',  'price', 'picture',]  # Picture is manual

    def clean(self) :
        cleaned_data = super().clean()
        pic = cleaned_data.get('picture')
        if pic is None : return
        if len(pic) > self.max_upload_limit:
            self.add_error('picture', "File must be < "+self.max_upload_limit_text+" bytes")

    def save(self, commit=True) :
        instance = super(CreateForm, self).save(commit=False)

        # We only need to adjust picture if it is a freshly uploaded file
        f = instance.picture   # Make a copy
        if isinstance(f, InMemoryUploadedFile):  # Extract data from the form to the model
            bytearr = f.read();
            instance.content_type = f.content_type
            instance.picture = bytearr  # Overwrite with the actual image data

        if commit:
            instance.save()

        return instance
Example #2
0
class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)
    picture = forms.FileField(required=False,
                              label='File to Upload <= ' +
                              max_upload_limit_text)
    upload_field_name = 'picture'

    class Meta:
        model = Ad
        fields = ['title', 'text', 'price', 'picture']

    def clean(self):
        cleaned_data = super().clean()
        pic = cleaned_data.get('picture')
        if pic is None:
            return
        if len(pic) > self.max_upload_limit:
            self.add_error(
                'picture',
                "File must be < " + self.max_upload_limit_text + " bytes")

    def save(self, commit=True):
        instance = super(CreateForm, self).save(commit=False)

        f = instance.picture
        if isinstance(f, InMemoryUploadedFile):
            bytearr = f.read()
            instance.content_type = f.content_type
            instance.picture = bytearr

        if commit:
            instance.save()

        return instance
Example #3
0
class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)

    # Call this 'picture' so it gets copied from the form to the in-memory model
    # It will not be the "bytes", it will be the "InMemoryUploadedFile"
    # because we need to pull out things like content_type
    picture = forms.FileField(required=False,
                              label='File to Upload <= ' +
                              max_upload_limit_text)
    upload_field_name = 'picture'

    # Hint: this will need to be changed for use in the ads application :)
    class Meta:
        model = Ad
        fields = ['title', 'price', 'text', 'picture']  # Picture is manual

    # Validate the size of the picture
    def clean(self):
        cleaned_data = super().clean()
        pic = cleaned_data.get('picture')
        if pic is None:
            return
        if len(pic) > self.max_upload_limit:
            self.add_error(
                'picture',
                "File must be < " + self.max_upload_limit_text + " bytes")

    # Convert uploaded File object to a picture
    def save(self, commit=True):
        instance = super(CreateForm, self).save(commit=False)

        # We only need to adjust picture if it is a freshly uploaded file
        f = instance.picture  # Make a copy
        if isinstance(f, InMemoryUploadedFile
                      ):  # Extract data from the form to the model
            bytearr = f.read()
            instance.content_type = f.content_type
            instance.picture = bytearr  # Overwrite with the actual image data

        if commit:
            instance.save()

        return instance


# https://docs.djangoproject.com/en/3.0/topics/http/file-uploads/
# https://stackoverflow.com/questions/2472422/django-file-upload-size-limit
# https://stackoverflow.com/questions/32007311/how-to-change-data-in-django-modelform
# https://docs.djangoproject.com/en/3.0/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other
Example #4
0
class CreateForm(forms.ModelForm):
    max_upload_limit = 2 * 1024 * 1024
    max_upload_limit_text = naturalsize(max_upload_limit)
    picture = forms.FileField(required=False,
                              label='File to Upload <= ' +
                              max_upload_limit_text)
    upload_field_name = 'picture'

    class Meta:
        model = Ad
        labels = {
            'text': 'Short description',
            'fulldesc': 'Full description',
        }
        fields = ['title', 'text', 'fulldesc', 'price', 'picture']

    def clean(self):
        """
        Validates the size of the picture
        :return: None
        """
        cleaned_data = super().clean()
        pic = cleaned_data.get('picture')
        if pic is None:
            return
        if len(pic) > self.max_upload_limit:
            self.add_error(
                'picture',
                "File must be < " + self.max_upload_limit_text + " bytes")

    def save(self, commit=True):
        """
        Converts uploaded File object to a picture
        :param commit: determines whether the record is committed to database
        :return: object instance
        """
        instance = super(CreateForm, self).save(commit=False)

        # We only need to adjust picture if it is a freshly uploaded file
        f = instance.picture  # Make a copy
        if isinstance(f, InMemoryUploadedFile
                      ):  # Extract data from the form to the model
            bytearr = f.read()
            instance.content_type = f.content_type
            instance.picture = bytearr  # Overwrite with the actual image data

        if commit:
            instance.save()

        return instance
Example #5
0
class ProfileForm(forms.ModelForm):
    max_upload_limit = 2 * 256 * 256
    max_upload_limit_text = naturalsize(max_upload_limit)
    picture = forms.ImageField(required=False,
                               label='File to Upload <= ' +
                               max_upload_limit_text)
    upload_field_name = 'picture'

    class Meta:
        model = UserProfile
        labels = {
            'home_address': 'Your home address',
            'phone_number': 'Phone number',
        }
        fields = ['home_address', 'phone_number', 'picture']
Example #6
0
class AdForm(forms.ModelForm):
    upload_limit = 2 << 10 << 10
    upload_limit_text = naturalsize(upload_limit)

    picture = forms.FileField(required=False,
                              label=f"File to Upload <= {upload_limit_text}")
    upload_field_name = 'picture'

    class Meta:
        model = Ad
        fields = ['title', 'price', 'text', 'picture']  # picture is manual

    def clean(self):
        # Validate the size of picture
        cleaned_data = super().clean()
        picture = cleaned_data.get('picture')
        if picture is None:
            return
        if len(picture) > self.upload_limit:
            self.add_error('picture',
                           f"File must be < {self.upload_limit_text}")

    def save(self, commit=False):
        # Convert uploaded file to a picture
        instance = super().save(commit=False)

        f = instance.picture
        if isinstance(f, InMemoryUploadedFile):
            byte_array = f.read()
            instance.content_type = f.content_type
            instance.picture = byte_array

        if commit:
            instance.save()

        return instance