1

In my model, I have a defined a FileField which my template displays it as a link. My problem is that the linked file displays the url as the name. What shows on html page is:

Uploaded File: ./picture.jpg

I've looked on the DjangoDocs regarding file names and a previous S.O. question, but just can't figure it out.

How can I:

  1. Have it display a different name, not a url.
  2. Allow the admin who uploaded the file to give it a name, which would then be viewed on the template.

my models.py:

class model_name(models.Model):
    attachment = models.FileField()

my views.py (if entry exists, display it, if not, return message):

from django.core.files import File
from vendor_db.models import model_name

def webpage(request, id):
    try:
        variable = model_name.objects.get(id=id)
    except model_name.DoesNotExist:
        raise Http404('This item does not exist')
    return render(request, 'page.html', {
        'variable': variable,
    })

my page.html:

<p>Uploaded File: <a href="{{ variable.attachment.url }}">{{ variable.attachment }}</a></p>
Hayden Crocker
  • 509
  • 4
  • 15
Kervvv
  • 751
  • 4
  • 14
  • 27

3 Answers3

2

For your code:

class model_name(models.Model):
    attachment = models.FileField()

attachment is a FileField object, that has a property called filename, so just ask for that property. i.e.

foo = model_name.objects.create(attachment=some_file)
foo.attachment.filename # filename as a string is returned
Hayden Crocker
  • 509
  • 4
  • 15
Aaron Lelevier
  • 19,850
  • 11
  • 76
  • 111
  • This has helped, but still having some trouble. I understand that I need to call the filename attire, but shouldn't i be calling that when define foo? Also where am I putting the second line of code? In the template? – Kervvv Mar 24 '16 at 17:46
1

In page.html:

<p>Uploaded File: <a href="{{ model.Attachment.url }}">{{ model.Attachment }}</a></p>

should be changed to:

<p>Uploaded File: {{ variable }}</p>
arrt_
  • 369
  • 1
  • 6
  • 15
  • You are right, I should be displaying just the variable, however, what I am defining that variable to be is the current issue that I am having right now. I wish i could up vote, but i don't have enough rep yet lol – Kervvv Mar 24 '16 at 17:48
0

To solve, I simply added an additional field to the models.py. This allows user to give it a name. and when displaying it on a page, call the Attachment and Attachment_Name as shown below. Hope this helps. No URL mess.

class model_name(models.Model):
    Attachment = models.FileField()
    Attachment_Name = models.CharField()

and in my html file:

<p>Uploaded File: <a href="{{ variable.Attachment.url }}">{{variable.Attachment_Name }}</a></p>
Kervvv
  • 751
  • 4
  • 14
  • 27