简体   繁体   中英

How to manipulate CharField as a string Django

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.

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)

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.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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM