Category Archives: Development

Clicking through links in a generic DetailView

Creating views in Django without much background in it can be a daunting task. Since I am working on an application to view and track fiber optic cables on campus, I wanted to be able to see what LAN rooms are in a building that I’m viewing using a generic DetailView.

To accomplish this, I found out that you can call on model relationships in order to see which models have a foreign key for the selected building.

Here is where I called the DetailView generic view in urls.py:

from django.views.generic import DetailView
...

# Buildings
    url(r'^buildings/(?P<pk>\d+)/$',
        DetailView.as_view(
            model=Building,
            template_name='fiberdb/buildings_detail.html')),

Here is what I placed in my template for buildings_detail.html to do this:

<ul>
    {% for lanroom in building.lanroom_set.all %}
    <li><a href="/lanrooms/{{ lanroom.id }}/">{{ lanroom.lan_room_name }}</a></li>
    {% endfor %}
</ul>

Calling lanroom_set.all on the building passed through to the template lets me list all of the LAN rooms in that building right on its DetailView page!

Final output looks like this:

Donnelly Hall

It took some hunting online to find the best way to do this, and this is what worked for me in the end! It’s worth noting that this will probably not be the most efficient way to access the database in this scenario, as it seems to require n+1 queries for the number of LAN rooms, but right now I am building things out before they are optimized.

Building an inventory system with Django

Originally posted on Tuesday, February 5, 2012 on michaelrudden.tumblr.com

I am currently working on building an inventory system for Marist College’s Networking department in order to track fiber around campus. I decided to use Django because I’ve never worked with it before and it is a powerful framework for developing web applications. Code for this is on my GitHub page! I also discovered Bootstrap, from Twitter, and am using that for a good looking front end. Now I just need to keep working on my views and soon I’ll have a great, functioning app that serves an important purpose.