How to split a string in Django template + Model

Why would you need this? In my example, I have a simple shopping list and since Sqlite doesn't support arrays, this is an easy was to iterate the items to a neat list.

Initial state

This didn't look nice

End state

This was better

Models.py

I added a custom method to my class to do the splitting.

#models.py

from django.db import models
from datetime import datetime
from django.contrib.auth.models import User

class List(models.Model):
    shop = models.CharField(max_length=100, default="")
    shop_items = models.TextField(default="")
    date = models.DateField(null=True, blank=True, default=datetime.today)
    shopper = models.ForeignKey(
            User,
            on_delete=models.CASCADE, default=""
        )
    done = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.shop} {self.date}"

    def get_absolute_url(self):
        return f"/shoppinglist/{self.pk}" 

    def shop_items_better_list(self): ##This is the method I'm writing aboout
        return self.shop_items.split('\n')

Template

To render the result in a web page I made a simple for-loop.

{% for item in shoppinglist.shop_items_better_list %}
    {{ item }}<br>
{% endfor %}

All articles


Comments

No published comments yet.


Add a Comment

Your comment is held for review before it appears publicly.

Your email is never published or shared.

Up to 2,000 characters.

Tick the box, then click Submit right away (Google expires the check after about two minutes).