开发者

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

I've got a model like this:

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

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

Question is: what is the right way to do it?

I couldn't find anything related in the docs, so I was looking at manually editing request.FILES before feeding it t开发者_运维百科o MyModelForm(), but this looks like a dirty hack to me... Any ideas?

Thanks.


I would store the code input in a CharField and then create a separate function that accesses the model and if the code does not contain any harmful methods it is then written to a file.

This takes care of creating the file (as a blank CharField will simply be outputted to an empty file) and allows for delegation to a security checker. Your setup would then look something like the following: Model:

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

View:

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 New view:

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")


Just set the field to allow null and blank. This will make the field optional.

code = models.FileField(null=True, blank=True)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜