Django-Provide a download from a function defined in a model -


i trying implement view, logged in user has uploaded file can download file, his, not other users files, don't create id url based on pk of file . result in views query test_result_file table , filter specific user. think can want writing function in model:

class test_result_file(models.model):     user=models.foreignkey(user)     system=models.foreignkey(system)     test_id=models.foreignkey(detail)     path=models.charfield(max_length=300)     class meta:         verbose_name="test result file"         verbose_name_plural="test result files"     def get_self(self):         path=self.path         wrapper = filewrapper(open( path, "r" ))         response=httpresponse(wrapper, content_type="text/plain")         response['content-disposition'] ='attachment; filename="results.txt"'         return response  

however, in template, when call:

     <ul>     {% @ in attempts %}     <li>system name: <em>"{{ at.system}}"</em>, download file: <a href="{{at.get_self}}">here</a> </li>      {% endfor %}</ul> 

the download not provided , instead browser tries open url parameters of response , fails. losing something? feasible function?

first point: response not url. want in template urls, not responses. second point: generating reponse responsability of view, not of model. side note : should respect python's coding conventions (cf pep08)

the rightway(tm) organize code be:

# myapp/models.py class testresultfile(models.model):     user=models.foreignkey(user)     system=models.foreignkey(system)     test_id=models.foreignkey(detail)     path=models.charfield(max_length=300)     class meta:         verbose_name="test result file"         verbose_name_plural="test result files"  # myapp/views.py def download_file(request, file_id):     testfile = get_object_or_404(testresultfile, pk=file_id)     wrapper = filewrapper(open(testfile.path, "r" ))     response=httpresponse(wrapper, content_type="text/plain")     response['content-disposition'] ='attachment; filename="results.txt"'     return response   # myapp/urls.py urlpatterns = patterns('',     url(r'^download/(?p<file_id>\d+)/?', 'views.download_file', 'myapp_download_file'),     # ...     )  # myapp/templates/myapp/template.html <ul> {% @ in attempts %}   <li>       system name: <em>"{{ at.system}}"</em>,        download file: <a href="{% url 'download_file' at.pk %}">here</a>    </li>  {% endfor %}  </ul> 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -