我有一个上传文件,它接收一个文本文件,并读取输入(contentOfFile)。
文件上传和读取数据工作正常(我已经测试过),但是在尝试使用此数据填充文本区域小部件时遇到问题。
views.py
uploaded1 = request.FILES['uploaded']
contentOfFile = uploaded1.read()
textInput1.innerHTML = contentOfFile
forms.py
class HomeForm(forms.Form):
textInput1 = forms.CharField(required=False, widget=forms.Textarea(
attrs={
'class': 'form-control',
}
))
class Meta:
fields = {'textInput1',}
template.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.textInput1 }}
<button type="submit" name="compare" class="btn btn-primary mb-2">Compare</button>
</form>
答案 0 :(得分:0)
花了一段时间,但设法弄清楚了。
文本小部件为 form.textInput1 ,而'uploaded1'是指模板中输入的文件。 我必须添加for循环,以防止文本区域在上传的文本之前显示为“ / b”。我认为这与从二进制类型转换有关,因此for循环将其手动转换为字符串
我希望这对以后的人有所帮助。
views.py:
form = HomeForm(initial=dict(foo=request.FILES))
if 'uploaded1' in request.FILES:
upload1 = request.FILES['uploaded1'].read()
data1 = ""
for x in upload1:
data1 = data1 + chr(x)
form.initial['textInput1'] = data1
args = {'uploaded1': upload1, 'form': form, }
if upload1:
return render(request, self.template_name, args)
template.html
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.textInput1 }}
<input type="file" name="uploaded1" accept=".txt"/>
<input type="submit" value="upload sample text" class="btn btn-primary mb-2"/>
</form>