我在 Django 中有一个表单,用户可以在其中以单个表单提交文件/图像/文本,如下所示。
<form id="send-form" action="{% url 'chat:message' context.room_id %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<table style="width: 100%">
<input type="hidden" name="from" value="{{ user }}">
<input type="hidden" name="next" value="{{ request.path }}">
<tr style="width: 100%">
<td style="width: 50%">
<input type="text" id="chat-input" autocomplete="off" placeholder="Say something" name="text" id="text"/>
</td>
<td style="width: 16%">
<input type="file" name="image" accept="image/*" id="image">
</td>
<td style="width: 16%">
<input type="file" name="file" accept="image/*" id="file">
</td>
<td style="width: 16%">
<input type="submit" id="chat-send-button" value="Send" />
</td>
</tr>
</table>
</form>
In views.py
,即使三个输入中的任何一个丢失,也必须提交表单,即,即使用户仅提交文本/仅图像/仅文件,数据也必须上传到数据库中,并且我在下面使用 try 和 except 编写方式:
def messages(request, room_id):
if request.method == 'POST':
try:
img = request.FILES['image']
except:
img = None
try:
text = request.POST['text']
except:
text = None
try:
file = request.FILES['file']
except:
file = None
path = request.POST['next']
fields = [img,file,text]
ChatMessage.objects.create(room=room,user=mfrom,text=text,document=file,image=img)
还有其他更好的方法吗?代码看起来不太好,除了所有的 try 之外。
更好的方法可以使用get
,如果字典中不存在该键,将返回第二个参数而不引发异常
这是关于这个主题的一个很好的答案->link https://stackoverflow.com/questions/11041405/why-dict-getkey-instead-of-dictkey
def messages(request, room_id):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES) # replace UploadFileForm with your form name
if form.is_valid(): # just check if the form is valid, i don't know if you are doing it before
img = request.FILES.get('image', None)
text = request.FILES.get('text', None)
file = request.FILES.get('file', None)
path = request.POST['next']
fields = [img, file, text]
ChatMessage.objects.create(
room=room,
user=mfrom,
text=text,
document=file,
image=img
)
else:
return render(request, 'upload.html', {'form': form})
这是一个草稿,但当然,这始终是在表单无效时将用户重定向回表单的好方法
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)