I’m using the regroup tag in a Django template to list a number of items, grouped by Customer. My model is:
class Customer(models.Model):
name = models.CharField(max_length=25)
city = models.CharField(max_length=25)
I can list the items customer.name (or customer.city), by what I really want is to order them as “Name, City”. According to the documentation “Any valid template lookup is a legal grouping attribute for the regroup tag, including methods, attributes, dictionary keys and list items.” [1] How to I define a method for this? And how do I call it from my template?
[1] https://docs.djangoproject.com/en/dev/ref/templates/builtins/
Update: As i understand the regroup functionality, and are using it now, I group the list using one of the object’s fields. The separator, customer.grouper, displays the name of that particular field. In my case “customer.name” or “customer.city”. My goal is to present this together, like “customer.name, customer.city” (i.e. “Microsoft, Redmond”). The documentation mentions this briefly but I cannot figure it out.
def display_name(self):
return "%s, %s" (self.name, self.city)
I have tried a method like above, as part of my Customer model, to fix my problem. But I’m not sure how to call it from my template.
Your model function is correct but it should contain a
%before the braces:Your view should pass a list of objects and not values.
Let the list be
tp, so your template code should be something like this:This should work out for you well enough.