【发布时间】:2021-02-13 14:29:56
【问题描述】:
我在 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)
还有其他更好的方法吗?包含所有尝试异常的代码看起来不太好。
【问题讨论】:
-
使用
.get(),如果键存在则返回值否则None这基本上是你正在做的,但是在一个方法调用中并且没有尝试/除:img = request.FILES.get('image')
标签: python django forms optimization