Addohm Addohm - 1 month ago 8
Python Question

Django Python Script

I've been sifting through the documention but I don't feel like I'm getting a clear answer. Is it possible to run something python-like

if company_name.startswith(('A')):
enter code here


from within a Django site or app? How would I go about it?

Currently the code I use is

{% for TblCompanies in object_list %}
<tr class="customer-table">
<td>{{ TblCompanies.company_id }}</td>
<td>{{ TblCompanies.company_name }}</td>
<td>{{ TblCompanies.contact_phone }}</td>
<td>{{ TblCompanies.billing_address }}</td>
<td>{{ TblCompanies.contact_e_mail }}</td>
</tr>
{% endfor %}


but our customer database is too large and it's a burden to have to go through the list to find a customer. I want to instead sort it alphabetically using urls like http://path/to/customer_list/A

Answer

Using slice filter, you can get a substring; then compare the substring with the 'A':

{% for TblCompanies in object_list %}
  {% if TblCompanies.company_name|slice:':1' == 'A' %}
  <tr class="customer-table">
    <td>{{ TblCompanies.company_id }}</td>
    <td>{{ TblCompanies.company_name }}</td>
    <td>{{ TblCompanies.contact_phone }}</td>
    <td>{{ TblCompanies.billing_address }}</td>
    <td>{{ TblCompanies.contact_e_mail }}</td>
  </tr>
  {% endif %}
{% endfor %}

As @Matthias commented, it would be better to pass filtered object_list in view. Assuming object_list is a queryset object:

object_list = object_list.filter(company_name__startswith='A')

Sorintg

Sort the object_list before passing it to the template:

page = requests.REQUEST.get('page', 'A')  # or Get from view parameter
                                          #    depending on url conf.
object_list = (object_list.filter(company_name__startswith=page)
                          .order_by('company_name'))

UPDATE

NOTE: Change app with actual app name.

urls.py:

url(r'^/path/to/site/customers/(?P<page>[A-Z])$', 'app.views.list_customers')

app/views.py:

from django.shortcuts import render

def list_compnaies(request, page):
    object_list = (Customer.objects.filter(company_name__startswith=page)
                           .order_by('company_name'))
    return render(request, 'customers/list.html', {
        'object_list': object_list,
    })

customers/list.html

{# Link to A .. Z customer pages %}
{% for page in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' %}
<a href="/path/to/site/customers/{{ page }}">{{ page }}</a>
{# Use {% url ... %} once you learn the url tag if possible to reduce duplicated hard-coded url #}
{% endif %}

{% for TblCompanies in object_list %}
<tr class="customer-table">
    <td>{{ TblCompanies.company_id }}</td>
    <td>{{ TblCompanies.company_name }}</td>
    <td>{{ TblCompanies.contact_phone }}</td>
    <td>{{ TblCompanies.billing_address }}</td>
    <td>{{ TblCompanies.contact_e_mail }}</td>
</tr>
{% endfor %}
Comments