Django FileField: how to set the default value (auto-create empty file)?

I have a model like this:

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    code = models.FileField()

When the new MyModel is introduced, I want to allow the code field to be left blank, in which case I need Django to create an empty file (with an arbitrary name).

Question: What is the right way to do this?

I could not find anything related in the documents, so I looked for manually editing request.FILES before loading it into MyModelForm (), but it looks like a dirty hack for me ... Any ideas?

Thank.

+3
source share
2 answers

CharField, , , , .

( CharField ) . : :

class MyModel(models.Model):
    name = models.CharField(max_length=255)
    code = models.CharField(MAX_FILE_LENGTH)

:

def Submit_Code(request):
     #Create MyModel using POST data
     process_input_file(NEWLY_CREATED_MODEL_NAME)
     return HttpResponse("Upload Successful")

def process_input_file(modelName):
     #assuming unique name. Use "id=" instead if needed.
     mm = MyModel.objects.get(name=modelName)
     if passes_security_checks(mm.code):
          f = open(mm.name, "r")
          f.write(mm.code)
          f.close()

Edit :

def Submit_Code(request):
     mm = MyModel()
     mm.name = request.POST.get('name')
     f = open(mm.name,"r")
     f.write(request.POST.get('code')
     f.close()
     #then associate the newly created file with the FileField however you want
     #passing through authentication/checking if need be.
     return HttpResponse("Upload Successful")
+2

null . .

code = models.FileField(null=True, blank=True)
+1

Source: https://habr.com/ru/post/1754125/


All Articles