How to get the name and url of an uploaded file?
I am using the following files:
settings.py:
MEDIA_URL = '/data/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'data')
urls.py:
urlpatterns = [
path("photo/upload", views.upload_pic, name="uploadpic ")
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py:
class Pic(models.Model):
name = models.CharField(max_length=255)
photo = models.FileField(upload_to="data/media/%Y/%m/%d")
def __str__(self):
return self.url
def path(self):
return self.url
forms.py:
from django import forms
class DocumentForm(forms.Form):
docfile = forms.FileField(
label='Select a file',
help_text='any valid file'
)
views.py:
def upload_pic(request):
documents = Pic.objects.all()
import uuid
name = uuid.uuid4().hex[:6].upper()
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
print(request.FILES)
newdoc = Pic(name=name, photo=request.FILES['docfile'])
newdoc.save()
return render(request, 'clinic/list.html', {'documents': documents, 'form': form, 'msg': 'success'})
else:
form = DocumentForm() # A empty, unbound form
return render(request, 'clinic/list.html', {'documents': documents, 'form': form})
template: clinic/list.html
{% extends 'clinic/newbase.html' %}
{% load static %}
{% block content %}
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: <a href="{{ uploaded_file_url }}">{{ uploaded_file_url }}</a></p>
{% endif %}
<p><a href="{% url 'index' %}">Return to home</a></p>
{% endblock %}
However in the rendered html, the urls are blank:
<body cz-shortcut-listen="true">
<!-- List of uploaded documents -->
<ul>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
<!-- Upload form. Note enctype attribute! -->
<form action="/clinic/photo/upload" method="post" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="EYTXeSgaP00jHNFhyPvgomYVyHB8FpTEXm5T4WrXCPyjpqkSrO3bEtiGQqV5iqeL">
<p></p>
<p><label for="id_docfile">Select a file:</label> max. 42 megabytes</p>
<p>
<input type="file" name="docfile" required="" id="id_docfile">
</p>
<p><input type="submit" value="Upload"></p>
</form>
<iframe frameborder="0" scrolling="no" style="background-color: transparent; border: 0px; display: none;"></iframe><div id="GOOGLE_INPUT_CHEXT_FLAG" input="" input_stat="{"tlang":true,"tsbc":true,"pun":true,"mk":true,"ss":true}" style="display: none;"></div></body>
How can I get the media name and url in the rendered template?
Sincerely yours,
Joel G Mathew