2016-10-18 3 views
2

모델에서 함수 정의를 호출 할 수 있다는 것을 알고 있지만 업로드 된 파일의 파일 이름을 추출 할 수 없습니다. 1Python Django 템플릿이 모델 함수에서 이름을 가져올 수 없습니다.

<form action="." method="GET"> 
{% if documents %} 
    <ul> 
     {% for document in documents %} 
     <li> {{ document.docfile.filename }} 
     <input type = "submit" name="load-data" value="Add to Layer"/> 
     </li> 
     {% endfor %} 
    </ul> 

결과

이 .html 버전 : 나는 다음과 같은 템플릿 형식하지만 내 원하는 출력에서 ​​두 결과를 시도 아래 그냥 버튼을 보여줍니다.

이 .html 버전 2

<form action="." method="GET"> 
{% if documents %} 
    <ul> 
     {% for document in documents %} 
     <li> {{ document.filename }} 
     <input type = "submit" name="load-data" value="Add to Layer"/> 
     </li> 
     {% endfor %} 
    </ul> 

결과 : 그것은 단지 버튼을 보여줍니다.

이 .html 버전 3

<form action="." method="GET"> 
{% if documents %} 
    <ul> 
     {% for document in documents %} 
     <li> {{ document.docfile.name }} 
     <input type = "submit" name="load-data" value="Add to Layer"/> 
     </li> 
     {% endfor %} 
    </ul> 

결과 : 전체 경로 이름을 인쇄합니다 (예 : /documents/2016/10/08/filename.csv) 함께 버튼을

나머지 코드는 다음과 같습니다.

models.py

class Document(models.Model): 
    docfile = models.FileField(upload_to='document/%Y/%m/%d') 

    def filename(self): 
     return os.path.basename(self.file.name) 

views.py

documents = Document.objects.all() 
return render(request, 'gridlock/upload-data.html', 
       { 
       'documents' : documents, 
       'form': form 
       }) 

나는 모든 것을 내가 노력하는 이유 누군가가 설명 할 수 있기를 바랍니다 : {{ document.docfile.filename }} 또는 {{document.file.filename}} 또는 {{document.filename}} 작업 중 하나를 나에게하지 않을 것이다? 감사!

+0

더 나은 방법은'템플릿 tag' 대신 편집 모델을 만드는 것입니다. 위의 대답에서 [SO Post] [1]을 확인하십시오. 템플릿 태그 생성에 대한 답변을 찾을 수 있습니다. [1] : http://stackoverflow.com/questions/2683621/django-filefield-return-filename-only-in-template – cutteeth

답변

4

나는 당신이 사용할 필요가 있으므로, 필드 DOCFILE라고하여 모델

def filename(self): 
    # try printing the filename here to see if it works 
    print (os.path.basename(self.docfile.name)) 
    return os.path.basename(self.docfile.name) 

def filename(self): 
    return os.path.basename(self.file.name) 

을 변경해야 당신이 당신의 모델을 제외하고, {{ document.filename }} 꽤 가까운 것 같아 self.docfile을 사용하여 값을 가져옵니다.

소스 : django filefield return filename only in template

+0

감사합니다! 이것은 정답입니다! 방금 연결 한 참조를 읽을 것입니다! – Reiion

+0

오오 지금 받으십시오. 그게 모델 아래서 나를 혼란스럽게 만들었 어! 다시 한 번 감사드립니다! – Reiion

관련 문제