Django 3.1.5
class PhpFile(models.Model):
subdir = models.CharField(max_length=255,
null=False,
blank=False,
unique=True,
verbose_name="Subdir")
file = models.FileField(upload_to=php_upload_to,
verbose_name="PHP file",)
class ReadonlyFiledsForExistingObjectsMixin():
"""
Disable a field "subdir" when modifying an object,
but make it required when adding new object.
"""
def get_readonly_fields(self, request, obj=None):
if obj: # editing an existing object
return self.readonly_fields + ('subdir',)
return self.readonly_fields
@admin.register(PhpFile)
class PhpFileAdmin(ReadonlyFiledsForExistingObjectsMixin,
admin.ModelAdmin):
form = PhpFileForm
exclude = []
class PhpFileForm(ModelForm):
def clean_file(self, *args, **kwargs):
if "file" in self.changed_data:
uploading_file = self.cleaned_data['file'].name
subdir = self.cleaned_data['subdir']
upload_to = get_upload_to(subdir, uploading_file, FILE_TYPES.PHP)
file = os.path.join(MEDIA_ROOT, upload_to)
if os.path.isfile(file):
raise ValidationError(
"File already exists. Change its version or don't upload it.")
return self.cleaned_data['file'] # File doesn't exist.
I want files to be concentrated in subdirs. So, a model contains a subdir field. And I want to check if a file has already been uploaded. If it has been, I raise validation error.
This code works only if I don't use ReadonlyFiledsForExistingObjectsMixin. If I uncomment it, subdir is not visible in the cleaned_data.
Could you help me organize both:
- Readonly subdir field for existing objects.
- Validation for existence of a file with such a name.
question from:
https://stackoverflow.com/questions/65950908/validate-file-existence 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…