rxmxn
rxmxn

Reputation: 499

Filtering field in DJango in the URL and in the view

Lets say I have a model with 2 fields:

class Bands(models.Model):
    id = models.IntegerField(db_column='ID', primary_key=True)
    name = models.CharField(db_column='NAME')
    type = models.CharField(db_column='TYPE')
    ...

What I want to do is to list all the fields data with just one template. For example:

{% block content %}

{{ field_name }}
    <ul>
    {% for band in bands %}
        <li>{{ band }}</li>
    {% endfor %}
    </ul>

{% endblock %}

So, how should I make my url?

url(r'^band/$', views.band, name='band')

or

url(r'^band/(?P<band>\w+)/$', views.band, name='band')

The link to that page would be:

<a href="{% url 'band' 'name' %}">Name</a>

In the view I'm taking the values as this:

def band(request, field):
    results = Results.objects.all()
    names = [n.name for n in results]
    types = [t.type for t in results]

    if field == 'name':
        bands = names
    else:
        bands = types

    return render(request, 'band.html', {'bands': bands, 'field_name': field})

Is this the right way to do this (in the view and the url)? Thanks in advance.

Upvotes: 3

Views: 127

Answers (1)

Josh K
Josh K

Reputation: 28883

Well, the simplest thing to do is use the DetailView.

from .models import Band

class BandDetailView(DetailView):
    model = Band

And in urls.py something like:

from band.views import BandDetailView
url(r'^band/(?P<pk>\d+)/?$', BandDetailView.as_view(), name='band-detail')

And in the template:

{% url 'band-detail' pk=1 %}

That said, your model doesn't make much sense to me, as does the Led Zeppelin vs. Deep Purple bits in the view. Can you explain your project / need a bit more?

Upvotes: 1

Related Questions