gpt4 book ai didi

python - 如何在 Django 中获取名称输入类型提交模型表单

转载 作者:行者123 更新时间:2023-12-04 07:14:25 26 4
gpt4 key购买 nike

我正面临一个问题。请帮我
模板.html

<form action="" method="POST">{% csrf_token %}
{{Form.as_p}}
<input type="submit" name="Save" value="Save">
<input type="submit" name="Delete" value="Delete">
</form>
查看.py
基于类的 View :
def post(self,request,text_id):
try:
text_data = Text.objects.get(pk=text_id)
a = FormText(request.POST,instance=text_data)
except:
a = FormText(request.POST)

if request.POST.get('name') =='Delete':
a.delete()
else:
try:
a.save()
except:
return HttpResponse('no ok')

最佳答案

您可以将其添加到按钮中,因此:

<form action="" method="POST">
{% csrf_token %}
{{Form.as_p}}
<button type="submit" name="action" value="save">Save</button>
<button type="submit" name="action" value="delete">Delete</button>
</form>
然后在您的 View 中,您可以访问 action 的值 key :
from django.shortcuts import get_object_or_404

def post(self,request,text_id):
item = get_object_or_404(Text, pk=text_id)
action = request.POST.get('action')
if action == 'delete':
item.delete()
# …
pass
elif action == 'save':
# …
pass
else:
# invalid action …
pass

关于python - 如何在 Django 中获取名称输入类型提交模型表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68872914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com