gpt4 book ai didi

python - 如何在 Django 中提交带有 href 的表单?

转载 作者:太空狗 更新时间:2023-10-30 03:00:55 26 4
gpt4 key购买 nike

我有一个链接,单击该链接后,应通过发布请求提交包含不可见字段的表单。然后我应该能够得到像这样的字段值:

var = request.POST.get('name_of_var', '')

看了几个帖子后,我似乎无法让它工作。这是我目前所拥有的:

<form id="form-id" method="post">
<li>
<input type="hidden" value="{{ obj }}" name="name_of_var">
<a href="/activities" onclick="document.getElementById('form-id').submit();"> {{obj}} </a>
</li>
</form>

在我看来,我有类似的东西,但从未触发过 POST 请求。这里可能是什么问题?:

if request.POST:
var = request.POST.get('name_of_var', '')
return render_to_response('activities/display_activities.html', var)

编辑:这是我的views.py:

def index(request):
if request.method == "POST":
var = request.POST.get('name_of_var', '')
return render_to_response('activities/display_activities.html', var)

category1 = Service.objects.filter(category = 'Sports')
category2 = Service.objects.filter(category = 'Dance')
category3 = Service.objects.filter(category = 'Music')
category4 = Service.objects.filter(category = 'Academics')
category5 = Service.objects.filter(category = 'Art')
category6 = Service.objects.filter(category = 'College')

subcat1 = []
subcat2 = []
subcat3 = []
subcat4 = []
subcat5 = []
subcat6 = []

for obj in category1:
subcat1.append(obj.subcategory)
subcat1 = list(set(subcat1))

for obj in category2:
subcat2.append(obj.subcategory)
subcat2 = list(set(subcat2))

for obj in category3:
subcat3.append(obj.subcategory)
subcat3 = list(set(subcat3))

for obj in category4:
subcat4.append(obj.subcategory)
subcat4 = list(set(subcat4))

for obj in category5:
subcat5.append(obj.subcategory)
subcat5 = list(set(subcat5))

for obj in category6:
subcat6.append(obj.subcategory)
subcat6 = list(set(subcat6))

return render_to_response('activities/activities.html', {'user': request.user,
'category1':category1, 'category2':category2, 'category3':category3,
'category4':category4, 'category5':category5, 'category6':category6,
'subcat1':subcat1,'subcat2':subcat2, 'subcat3':subcat3,
'subcat4':subcat4, 'subcat5':subcat5,'subcat6':subcat6 })

最佳答案

这就是我最终解决这个问题的方式。下面是一个与我原来的帖子完全不同的例子。注意:将 id 和 action 替换为您的相关代码。在我的示例中,{{form4}} 通过 View 传入,并且是我的 forms.py 中的一个自定义表单,只有一个字段。

<form id = "form-id" action="/events/attending" method="post">{% csrf_token %}
<a href="#" onclick="document.forms['form-id'].submit();" > Submit </a>
{{form4.going}} I am attending this event!
</form>

关于python - 如何在 Django 中提交带有 href 的表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27496425/

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