Reputation: 193
I have a charfield in which the user inputs a range of numbers which will correspond to a list of numbers. For example the user should be able to input '1, 2, 3, 4, 5' or '1-5', and I want to be able to convert that into a list of all those numbers in the range. When I grab the field's cleaned_data in the views.py, however, the value does not behave like a string. The .split() does not convert to a list, and the for loop loops through individual characters. How can I convert the field into a usable string?
In the views.py:
def my_view(request):
if request.method == 'POST':
if form.is_valid():
nums = form.cleaned_data['numbers']
nums.split(',')
num_list = []
for item in nums:
if '-' in item:
item.split('-')
for x in range(item[0], item[1]):
num_list.append(x)
else:
num_list.append(item)
If the input is '1-160', I get an error because the single character '-' can't be split into two items and be indexed. The expected num_list is a list of all the integers between 1 and 160.
If the input is '1,2,3' num_list is a list of all the characters, not just the numbers.
Upvotes: 2
Views: 195
Reputation: 476768
nums.split(',')
does not convert nums
of strings, it returns a list of strings, so you should work with:
def my_view(request):
if request.method == 'POST':
if form.is_valid():
nums = form.cleaned_data['numbers']
# ↓ assign the list, for example to nums
nums = nums.split(',')
num_list = []
for item in nums:
if '-' in item:
item.split('-')
for x in range(item[0], item[1]):
num_list.append(x)
else:
num_list.append(item)
Upvotes: 1
Reputation: 5746
split()
does not work in-place, it returns a list.
This means you need to assign a variable for the return value.
nums = nums.split(',')
def my_view(request):
if request.method == 'POST':
if form.is_valid():
nums = form.cleaned_data['numbers']
nums = nums.split(',')
num_list = []
for item in nums:
if '-' in item:
item.split('-')
for x in range(item[0], item[1]):
num_list.append(x)
else:
num_list.append(item)
Upvotes: 2