gpt4 book ai didi

Django访问表单集数据

转载 作者:行者123 更新时间:2023-12-04 05:31:29 24 4
gpt4 key购买 nike

我无法访问通过表单集提交的数据。这是我的代码:

模板:

<form action="" method="post">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}

{{ form.as_p }}

{% endfor %}

<input type="submit" value="Submit">

</form>

看法:
def addMembers(request, id, members):
if request.user.is_authenticated():
members = int(members)
MemberFormSet = formset_factory(MemberForm, extra = members)
if request.method == 'POST':
print 'post'
formset = MemberFormSet(request.POST)
if formset.is_valid():
cd = formset.cleaned_data
for f in formset:
first_name = cd.first_name
last_name = cd.last_name
email = cd.email
house = House.objects.get(id = id)
member = Member(first_name = first_name, last_name = last_name, email = email, house = house, created_on = timezone.now())
member.save()
return HttpResponseRedirect(reverse('houses:controlPanel'))
else:
formset = MemberFormSet()
return render_to_response('houses/add_members.html', {'formset' : formset}, context_instance = RequestContext(request))
return HttpResponseRedirect(reverse('allauth.account.views.login'))

除了当前编写的内容外,我还尝试了几种访问数据的方法,包括: f['attribute'] cd['attribute'] request.POST['attribute'] formset.cleaned_data['attribute']
我收到从 u"Key 'email' not found in Form"list indices must be integers, not str的错误

我应该如何访问表单集提交的数据? Django的文档未能对此给出清晰的答案,在搜索中我发现了许多不同的方法,但尚未奏效。谢谢你的帮助。

最佳答案

cd是字典。另外,您可能想从单个表单而不是表单集中获取字典值

if request.method == 'POST':
formset = MemberFormSet(request.POST)
if formset.is_valid():
for f in formset:
cd = f.cleaned_data
first_name = cd.get('first_name')
last_name = cd.get('last_name')
email = cd.get('email')
house = House.objects.get(id = id)
member = Member(first_name = first_name, last_name = last_name, email = email, house = house, created_on = timezone.now())
member.save()
return HttpResponseRedirect(reverse('houses:controlPanel'))

关于Django访问表单集数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18362994/

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