ChocoBomb
ChocoBomb

Reputation: 301

Use clean() method with Django

I'm wondering how I can set a clean method in my form, because I believed my function was well-written, but I don't overcome to get the expected result.

I have a simple model :

class Document(models.Model):
    ...
    format = models.CharField(max_length=10, verbose_name=_('format'), choices=FORMAT_CHOICES, null=False, blank=False)
    upload = models.FileField(upload_to='media/files/', validators=[validate_file_extension], verbose_name=_('document file'), null=False, blank=False)

I have a form :

class DocumentForm(forms.ModelForm):

    def clean(self):
        cleaned_data = super().clean()
        upload = cleaned_data.get("upload")
        file_format = upload.split(".")[-1]
        format = cleaned_data.get("format")
        if upload and format:
            if format != file_format:
                raise forms.ValidationError("Incorrect format and file format")

    def __init__(self, *args, **kwargs):
        super(DocumentForm, self).__init__(*args, **kwargs)

        for key in self.fields:
            self.fields[key].required = True

    class Meta:
        model = Document
        fields = ['format', 'upload']

This method has to check if choosen format and file upload extension are the same or not. If not, it should return an error.

I got this issue :

'TemporaryUploadedFile' object has no attribute 'split'

Do you have any idea about how I can check if both fields are correct ?

Upvotes: 1

Views: 269

Answers (1)

mr MaxSimka
mr MaxSimka

Reputation: 61

You should split file name, not the TemporaryUploadedFile object to get an extension. Try to use upload.name to get file name.

Upvotes: 3

Related Questions