如何在Django列表中添加按钮将数据写入HTML TextField用于短信发送
实现方案
第一步:修改模板按钮部分
找到sms_main.html里的BUTTON HERE位置,替换为以下代码:
<td width="1%"> <button type="button" class="select-btn" data-phone="{{ contact.num }}" style="padding: 2px 8px; cursor: pointer;"> 选择 </button> </td>
第二步:添加JS逻辑
在sms_main.html的</body>标签前添加以下JS代码:
<script> // 取收件人输入框元素 const contactsInput = document.querySelector('textarea[name="contacts"]'); // 取所有选择按钮 const selectBtns = document.querySelectorAll('.select-btn'); // 绑定按钮点击事件 selectBtns.forEach(btn => { btn.addEventListener('click', function() { const currentPhone = this.dataset.phone; // 把现有收件人拆成数组并过滤空值 let existingNumbers = contactsInput.value.split(',').filter(num => num.trim() !== ''); if (existingNumbers.includes(currentPhone)) { // 已选中则移除该号码,恢复按钮默认样式 existingNumbers = existingNumbers.filter(num => num !== currentPhone); this.style.backgroundColor = ''; this.style.color = ''; this.textContent = '选择'; } else { // 未选中则添加该号码,标记按钮选中状态 existingNumbers.push(currentPhone); this.style.backgroundColor = '#5498C2'; this.style.color = '#fff'; this.textContent = '已选'; } // 重新拼接为逗号分隔的字符串回填到输入框 contactsInput.value = existingNumbers.join(','); }) }) // 补全你原有代码里的展开/收起表格函数,避免运行报错 function hideFn() { const table = document.getElementById('theTable'); const icon = document.getElementById('iconLa'); if (table.style.display === 'none') { table.style.display = 'block'; icon.textContent = 'expand_less'; } else { table.style.display = 'none'; icon.textContent = 'expand_more'; } } </script>
现有代码优化建议
- 你的views.py中composeSMS函数建议增加POST请求判断,同时补全GET请求逻辑,避免直接访问页面时报错:
def composeSMS(request): if request.method == "POST": text = request.POST.get('smsArea', '') recipients = request.POST.get('contacts', '') # 原有发送短信的逻辑保持不变 sms = requests.post( "<api-endpoint>", data={'token': '<api-key>', 'from': 'Company', 'to': recipients, 'text': text}) sms_status_code = sms.status_code sms_response = sms.text sms_response_json = sms.json() context = {'sms': sms} return render(request, "sms_sent.html", context) else: # GET请求时查询所有患者数据传给模板渲染列表 contacts = Patient.objects.all() return render(request, "sms_main.html", {"contacts": contacts})
- 现有Sms模型的recipients字段用了ForeignKey,只能关联单个患者,如果需要存储多个收件人记录,建议改为
models.ManyToManyField(Patient)。
内容的提问来源于stack exchange,提问作者Bhaskar Rijal
相关产品推荐
相关产品推荐

