In my Django App there is a page where users can upload files from their local machine (and do other things).
The flow I built is so that users click on " ", a modal form comes up, users browse for a file on their local machine, select it and when they click save I submit the form.
However, for some reason, the file isn't getting posted but it seems like I am posting only the name of the file. But I can't figure out why.
file page
...
<div >
<a href="#" data-bs-toggle="modal" data-bs-target="#modal">
<img src="{% static 'action/img/project/files/icon_plus-file.svg' %}" alt=" ">
</a>
</div>
{% include 'action/forms/modals/modal.html' %}
modal.html
<div tabindex="-1" role="dialog" id="modal" >
<div role="document">
<div >
<!-- Popup -->
<div >
<div >
<!-- Title -->
<div >
<h2 >Dialog Title</h2>
</div>
<!-- END Title -->
<!-- Form -->
<form action="{% url 'action:project_files' project_id=project.id %}" method="POST" >
{% csrf_token %}
<!-- Input File Name -->
<div >
<label for="fileName">File Name</label>
<input id="fileName" name="fileName" type="text" placeholder="File Name">
</div>
<!-- END Input File Name -->
<!-- Input Link -->
<div >
<!-- Link -->
<div >
<label for="inputLink">Link</label>
<input id="inputLink" name="inputLink" type="text" placeholder="https://">
</div>
<!-- END Link -->
<!-- Local File Name -->
<div >
<img src="{% static 'action/img/project/files/icon_paperclip-solid.svg' %}" alt="Added">
<input type="text" id="fileNameLocal" disabled>
<span id="deleteFile">
<img src="{% static 'action/img/project/files/icon_close-inputfile.svg'%}" alt="Close">
</span>
</div>
<!-- END Local File Name -->
</div>
<!-- END Input Link -->
<!-- WRP Text & Upload -->
<div >
<p >OR</p>
<div >
<label>
<input type="file" name="userfile[]">
<span>Browse</span>
</label>
</div>
</div>
<!-- END WRP Text & Upload -->
<!-- BTNs -->
<div >
<button type="button" data-dismiss="modal">Close</button>
<button type="submit" >Save</button>
</div>
<!-- END BTNs -->
</form>
<!-- END Form -->
</div>
</div>
<!-- END Popup -->
</div>
</div>
</div>
view
class ProjectFiles(MyLoginRequiredMixin, TemplateView):
template_name = 'action/project/file.html'
def post(self, request, *args, **kwargs):
instance = get_object_or_404(JobProject, id=kwargs['project_id'])
if request.POST.get('userfile[]'):
file = request.FILES['userfile[]']
#Actually, the whole request.FILES is empty
CodePudding user response:
In your form, add the enctype to deal with files
<form action="{% url 'action:project_files' project_id=project.id %}" method="POST" enctype="multipart/form-data">
{% csrf_token %}
....


