我在 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>
在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)
有没有其他更好的方法来做到这一点。代码看起来不太好,除了所有的尝试之外。