1👍
✅
First point: a response is not an url. What you want in your template are urls, not responses. Second point: generating a reponse is the responsability of a view, not of a model. Side note : you should respect Python’s coding conventions (cf pep08)
The RightWay(tm) to organize your code would 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>
{% for at in attempts %}
<li>
System Name: <em>"{{ at.system}}"</em>,
download file: <a href="{% url 'download_file' at.pk %}">here</a>
</li>
{% endfor %}
</ul>
0👍
Maybe you can simply use somthing like this:
class userfile(model.Model):
user=models.ForeignKey(User)
file = models.FileField(_('file'), upload_to='userfile/', blank=False)
def __unicode__(self):
return "%s file" % user
and in you template:
{% if user.userfile_set.count > 0 %}
<ul>
{% for file in user.userfile_set.all %}
<li>File: <a href="{{MEDIA_URL}}{{file.file}}">{{file}} dowload it</a></li>
{% endfor %}
</ul>
{% else %}
You don't have any file
{% endif %}
I hop it can help you.
- [Answer]-How to send POST request with search term obtained from autocomplete in Django
- [Answer]-Set form's default values from existing objects in Django
- [Answer]-Does Django try to translate template variables?
- [Answer]-Modelform prepopulate foreign key
- [Answer]-Django-Simple-Friends all users not connected as friends
Source:stackexchange.com