S
S
Salavat Sharapov2014-04-29 11:47:53
Django
Salavat Sharapov, 2014-04-29 11:47:53

How to get the url to a file in django?

There is a model:

class TextTemplate(models.Model):
        title = models.CharField(max_length=255, verbose_name=u'Заголовок')
        text = models.TextField(verbose_name=u'Текст', null=True, blank=True)
        file_upload = models.FileField(upload_to='templates/', verbose_name=u'Файл', blank=True, null=True)

you need to get the url to the file uploaded in the file_upload field.
TextTemplate.objects.values? TextTemplate.objects.filter?
TextTemplate.object.file_upload.url?? - your thoughts, after reading djbook.ru (For example, if the ImageField is named mug_shot, you can get the URL to the file in the template using {{ object.mug_shot.url }}.)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sim3x, 2014-04-29
@desperadik

it is desirable to embed in the model

class TextTemplate(models.Model):
     ....
     def get_absolute_file_upload_url(self):
     return MEDIA_URL + self.file_upload.url

#urls.py
...
urlpatterns = patterns(
    '',
    url(r'^text-template/(?P<primary_key>\d+)/$', get_tt),
    url(r'^text-template/$', get_all_tt),
    )
...

#view.py
def get_tt(request, primary_key):
    tt_item = TextTemplate.objects.get(pk=primary_key)
    # or
    # tt_item = get_or_404(TextTemplate, pk=primary_key)
    print tt_item.file_upload.url
    return render('t.html', {'tt': tt_item})

def get_all_tt(request): 
    tt_all = TextTemplate.objects.all()
    for tt_item in tt_all:
         print tt_item.file_upload.url
    return render('tt-all.html', {'tt': tt_all})

#t.html
<img src="{{ MEDIA_URL }}{{ tt.url }}">
<br>
<img src="{{ tt.get_absolute_file_upload_url }}">

#tt-all.html
{% for tt in tt_all %}
<img src="{{ tt.get_absolute_file_upload_url }}">
{% endfor %}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question