[ django output writing to a text file as temporary storage (over-written with each submission) ]
I have managed to configure a system, using django, that allows me to upload a file to my media-folder. I have (using simple-html) included a drop-down menu that will specify parameters that will be considered when processing the uploaded file in a pipeline.
<form action="{% url "list" %}" method="post" enctype="multipart/form-data">
<tr>
{% csrf_token %}
<p>{{ form.non_field_errors }}</p>
<p>{{ form.docfile.label_tag }} {{ form.docfile.help_text }}</p>
<p>
{{ form.docfile.errors }}
{{ form.docfile }}
</p>
</tr>
<tr>
<th>Genome Dataset</th>
<TD WIDTH = 80% ALIGN=left VALIGN=top>
<SELECT NAME='genome' ID='genome'>
<OPTION>All</OPTION>
<OPTION>Neanderthal</OPTION>
<OPTION>hg38 Human</OPTION>
<OPTION>Denisovan</OPTION>
</SELECT>
</tr>
<p><input type="submit" value="Upload"/></p>
</form>
I need to send the selected dropdown option to a text file. and I have attempted to do so as follows in views.py. However. while the file uploads to the media folder successfully, no text file manifests in the media folder- which is needed.
def GenomesView(request):
if request.method == 'GET':
getgen = request.GET.get('genome')
content = ContentFile(getgen)
f = open(os.path.join(settings.MEDIA_ROOT, 'file.txt'), 'w')
myfile = File(f)
myfile.write(getgen)
myfile.close()
The location of the media folder is as below in settings.
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
Hence my question is how do I take the selected option forms the drop-down and each time the file is uploaded to the site, the selection is sent to text file that will be over-written for each new submission (acting as a temporary storage for the selected option parameter i.e "Neanderthall" etc. as seen in code above)?
Answer 1
It looks like you are using a form to POST this data, but only writing to the file if the request is a GET. Try changing it to a POST. Also, since request.POST.get('genome')
should return a string for you to write to the file there is no need to wrap it in a ContentFile
. Try this:
if request.method == 'POST':
getgen = request.POST.get('genome')
with open(os.path.join(settings.MEDIA_ROOT, 'file.txt'), 'w') as f:
f.write(getgen)
I also changed your file handling to use a context manager.