tags:

views:

110

answers:

1

Hi,

I have 2 models which look like that:

class Entry(models.Model):
user = models.ForeignKey(User)
dataname = models.TextField()
datadesc = models.TextField()
timestamp = models.DateTimeField(auto_now=True)

class EntryFile(models.Model):
    entry = models.ForeignKey(Entry)
    datafile = models.FileField(upload_to="uploads/%Y/%m/%d/%H-%M-%S")

I want to render all the entries with their related files for a specific user. Now I am doing it that way in my view to get the values:

    entries = Entry.objects.filter(user=request.user).order_by("-timestamp")
    files = {}
    for entry in entries:
     entryfiles = EntryFile.objects.filter(entry=entry)
     files[entry] = entryfiles
    return render_to_response("index.html", {'user': request.user, 'entries': entries, 'files': files, 'message': message})

But I am not able/don't know how to work with these data in my template. This what I do now, but isn't working:

{% for entry in entries %}
 <td>{{ entry.datadesc }}</td>
 <td><table>
  {{ files.entry }}
  {% for file in files.entry %}
  <td>{{ file.datafile.name|split:"/"|last }}</td>
  <td>{{ file.datafile.size|filesizeformat }}</td>
  <td><a href="{{ object.datafile.url }}">download</a></td>
  <td><a href="{% url main.views.delete object.id %}">delete</a></td>
  {% endfor %}
 </table></td>
{% endfor %}

Anyone can tell me if I am doing it the right way in view and then how to access these data in the template?

Thank you!

+5  A: 

Just cut your view code to this line:

entries = Entry.objects.filter(user=request.user).order_by("-timestamp")

And do this in the template:

{% for entry in entries %}
    <td>{{ entry.datadesc }}</td>
    <td><table>
    {% for file in entry.entryfile_set.all %}
        <td>{{ file.datafile.name|split:"/"|last }}</td>
        <td>{{ file.datafile.size|filesizeformat }}</td>
        <td><a href="{{ object.datafile.url }}">download</a></td>
        <td><a href="{% url main.views.delete object.id %}">delete</a></td>
    {% endfor %}
    </table></td>
{% endfor %}

I am a big fan of using related_name in Models, however, so you could change this line:

entry = models.ForeignKey(Entry)

To this:

entry = models.ForeignKey(Entry, related_name='files')

And then you can access all the files for a particular entry by changing this:

{% for file in files.entryfile_set.all %}

To the more readable/obvious:

{% for file in entry.files.all %}
Paolo Bergantino
It's working great now. Thank you!
e-Jah
No problem. Welcome to the site.
Paolo Bergantino
Thank you for the greetings :)
e-Jah