【问题标题】:Get 'str' into Djano forms.FileField()获取'字符串到 Django forms.FileField()
【发布时间】:2021-12-19 05:37:27
【问题描述】:

我正在上传没有表单。 如果我通过<input type...> 上传,我的用户有一个 FileField,我没有问题。 但这对我的目的来说不是那么方便。

views.py

    def uploadaction2(request):
        f = forms.FileField() # this is my idea
        data = json.loads(request.body)
        # f.clean("data['data']") # error: file_name = data.name AttributeError: 'str' object has no attribute 'name'
        logger.error(type(data['data'])) #gives <class 'str'> and without the type the string that i want to save
        with open('newfile', 'w') as file:
            file.write(data['data'])
        request.user.file = file 
        request.user.save() # i get no error until this part

错误

Internal Server Error: ....  in pre_save
    if file and not file._committed:
AttributeError: '_io.TextIOWrapper' object has no attribute '_committed'

我想我必须将 json 字符串转换为 forms.FileField(),因为我不知道该怎么做。

【问题讨论】:

    标签: python django forms model


    【解决方案1】:
        def uploadaction2(request):
            file = request.FILES.get('file') # set name to input
            request.user.file = file
            request.user.save()
    

    【讨论】:

    • logger.error(request.FILES.get('file')) -> 返回无。因为我发送的不是文件,而是一个字符串,而这个字符串到达​​了我的后端。
    • 只需将相对文件路径字符串设置为用户的文件字段。
    猜你喜欢
    • 2012-04-20
    • 2011-05-20
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-20
    • 2012-03-20
    相关资源
    最近更新 更多