Consider a Django model with a FileField. When a user uploads a file through a form linked to this model, what is the default behavior regarding the file storage?
class Document(models.Model): upload = models.FileField(upload_to='uploads/')
Think about where Django stores uploaded files by default when using FileField.
Django saves uploaded files to the filesystem under the MEDIA_ROOT directory combined with the upload_to path. It does not store files in the database or temporary folders by default.
Which of the following Django view snippets correctly handles a file upload from a form?
def upload_file(request): if request.method == 'POST': form = UploadForm(request.POST, request.FILES) if form.is_valid(): # What should happen here? pass else: form = UploadForm() return render(request, 'upload.html', {'form': form})
Remember that uploaded files are in request.FILES and you can assign them to model fields before saving.
Uploaded files are accessed via request.FILES. You create a model instance, assign the file to the FileField, then save the instance. Option A correctly does this.
Examine the following Django view code snippet. It raises a MultiValueDictKeyError when no file is uploaded. Why?
def upload_file(request): if request.method == 'POST': file = request.FILES['file'] instance = Document(upload=file) instance.save() return render(request, 'upload.html')
Think about what happens if the form is submitted without a file.
Accessing request.FILES['file'] directly causes a MultiValueDictKeyError if the key 'file' is missing. Using request.FILES.get('file') or checking if the key exists avoids this error.
Given this Django model and view, what will be the value of instance.upload.name after saving a file named example.txt?
class Document(models.Model): upload = models.FileField(upload_to='docs/') def upload_file(request): if request.method == 'POST': file = request.FILES['file'] instance = Document(upload=file) instance.save() return instance.upload.name
Remember that upload_to sets a folder path relative to MEDIA_ROOT.
The upload.name property returns the relative path including the upload_to folder and the filename. It does not include MEDIA_ROOT or a leading slash.
request.FILES instead of request.POST for file uploads in Django?When handling file uploads in Django, why must you access uploaded files via request.FILES instead of request.POST?
Think about how browsers send files in forms and how Django separates data.
Files uploaded via forms are sent in a separate part of the request and are accessible in Django through request.FILES as UploadedFile objects. request.POST only contains text data from form fields.