filter(id__in=[ids])“字段'id'应该是一个数字,但得到了1,2”JavaScript和Django

gajydyqb  于 2023-02-17  发布在  Go
关注(0)|答案(2)|浏览(140)

我尝试设置类别为我的职位没有一个形式,与javascript
模板:

<form enctype="multipart/form-data" method="POST" action="" accept=".mp4" style="text-align: center;">
    {% csrf_token %}
    <p style="color: gray; padding-top: 20px;">or</p>
    <select name="" id="ms" multiple="multiple">
    {% for category in categories%}
            <!-- <option type="checkbox" value="{{category}}">{{category}}</option> -->
            <input id="category" class="category" catid="{{category.id}}" type="checkbox" value="{{category.id}}">{{category}}</input>
            {% endfor %}
    </select>
    <input type="text" name="title" id="title" placeholder="Title">
    <input type="text" name="tags" id="tags" placeholder="Tags: Please separate by comma ','">
    <textarea name="description" id="description" cols="30" rows="10" placeholder="Please describe your video..."></textarea>
    <div class="form-group">
            <label>Select file to upload.</label>
            <input type="file" name="file" accept=".mp4" class="form-control" id="fileupload" placeholder="Select file">
    </div>
    <input type="submit" value="Upload" id="submit" class="btn btn-success">     
</form>

约旦:

var id_categories = []; 
    var category = document.querySelectorAll("input[type=checkbox]:checked")
    for (var i = 0; i < category.length; i++) {
        id_categories.push(category[i].value)
      }
    var formData = new FormData();
    formData.append('categories', id_categories)

我认为:

categories_1 = Category.objects.all()
if request.method == 'POST':
 categories = request.POST['categories']
 FileFolder.save()
 tag_list = taggit.utils._parse_tags(tags)
 FileFolder.tags.add(*tag_list)
 categories_post = Category.objects.filter(id__in=[categories])
            if categories_post:
                for category in categories_post:
                    FileFolder.categories.add(category)
return render(request, 'main/create_post.html', {'categories': categories_1})

它返回:
ValueError:字段"id"应为数字,但得到的却是"3,4"。
但是当我手动输入[3,4]时,它工作了,有什么想法吗?

tf7tbtn2

tf7tbtn21#

    • categories = request. POST ['categories ']**是否强制转换为列表?可能您有字符串['3,4']的列表
categories = parse_ids(request.POST['categories'])
def parse_ids(ids: str):
    result = []
    for id in ids.split(','):
        try:
            result.append(int(id))
        except ValueError:
            pass
    return result
d5vmydt9

d5vmydt92#

看起来它得到的是字符串'3,4'而不是数字或数字数组
编辑:见那些“(双引号)标记中的“3”表示它是一个字符串。在Js:在第4行,您可以使用id_categories.push(parseInt(category[i].value) )而不是id_categories.push(category[i].value),但要确保输入只接受数字

相关问题