2013-08-21 196 views
8

我無法訪問通過我的模板提交的數據。這裏是我的代碼:Django訪問模板數據

模板:

<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

我該如何訪問由formset提交的數據? Django的文檔沒有給出明確的答案,並且四處搜索我發現了很多不同的方法,但都沒有工作。謝謝你的幫助。

回答

15

cd是一本字典。此外,您可能希望獲取從個體形式的字典中的值,而不是該formset

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')) 
+0

你不需要檢查'f.is_valid()'。除非所有表單都有效,否則表單無效。 –

+0

@PeterDeGlopper你是對的 – karthikr

+0

任何方式來檢查之前is_valid? – radtek

0

,我認爲你應該使用model_formsetfactory,甚至更好,一個inlineformset_factory。您正在從表單數據填充模型,這是它們的設計目的。從formset中獲取髒模型,使用commit = False,並添加到你的House關係中。類似這樣的:

MemberFormSet = model_formset_factory(Member, extra= members) 
if request.method == POST: 
    formset = MemberFormSet(request.POST) 
    if formset.is_valid(): 
     house = House.objects.get(id = id) 
     models = formset.save(commit=False) 
     for member in models: 
      member.house = house 
      member.save() 
     return render(<your data>) 
else: 
    formset = MemberFormSet() 
return render(<your data>) 

注意你的get()也會拋出一個異常,如果House對象不存在。只是一個設計考慮。