Reputation: 661
I'm trying to take an input that is a comma separated string value, store those items in a list for temporary display and use in a template. I'm currently having trouble storing each comma separated string value in a list, then displaying that list in a template.
A user inputs something similar into a database ModelForm field (without the quotes):
example input from a ModelForm
inputs = models.CharField(max_length=200)
Then the user would input something to the effect of
"length_ft,depth_in,width_in"
minus the quotes.
The following then sort-of works in the template:
{% for i in inputs_list %}
{{ i }}
{% endfor %}
Instead of displaying a list of list items, it simply lists each letter of each list item separately. I realize why, because I am stripping out commas, but then I'm trying to append the blank list with each csv item.
I don't understand how to get items out of the input string to a list, then to display in the template.
def test_formula(request, formula_id):
formula = Formula.objects.get(id=formula_id)
inputs_list = []
for inputs in formula.inputs:
strip = inputs.strip(",")
inputs_list.append(strip)
context = {'formula': formula, 'inputs_list': inputs_list}
return render(request, 'formulas/test_formula.html', context)
(this just breaks up each character into it's own item)
{% load static %}
{% block content %}
{% for i in inputs_list %}
{{ i }}
{% endfor %}
{% endblock content %}
formulas\urls.py
from django.urls import path
from . import views
urlpatterns = [
path('test_formula/<int:formula_id>', views.test_formula, name='test_formula'),
]
Upvotes: 0
Views: 3317
Reputation: 69725
Assuming you have a string of comma separated values such as "length_ft,depth_in,width_in"
, update your code to:
def test_formula(request, formula_id):
formula = Formula.objects.get(id=formula_id)
context = {'formula': formula, 'inputs_list': formula.inputs.split(",")}
return render(request, 'formulas/test_formula.html', context)
Basically, you need to us the str
method split
which returns a list of the words in the string, using the parameter that you pass as the delimiter string.
I would also suggest changing the variable i
to input
in the for in the template.
Upvotes: 1