Django模型表单设置初始值设置

时间:2011-11-04 18:50:31

标签: django django-forms

我注意到当我将初始值传递给我的模型formset(第100-102行)时,我无法从第二个formset开始发布item的值。

无法理解我的意思是该字段的值没有出现在我的request.POST和我的formset没有保存,因为它是必填字段。

当我删除lines100-102并正常提交表单时,它可以正常工作。

这些线有什么问题?

查看

 78 def registrant_details(request, event_slug, cart_id):
 79     '''
 80     Fill in user details for each item
 81     '''
 82     # check quantity between CartItem model and ItemUserDetails 
 83     event = get_object_or_404(Event, slug=event_slug)
 84     cart = get_object_or_404(Cart, id=cart_id)
 85     cart_items = CartItem.objects.filter(cart=cart)
 86 
 87     max_num = [cart_item.quantity for cart_item in cart_items]
 88 
 89     ItemUserDetailsFormset = modelformset_factory(ItemUserDetails, max_num=sum(max_num), extra=sum(max_num), exclude=['cart'])
 90 
 91     if request.method == 'POST':
 92         formset = ItemUserDetailsFormset(request.POST)
 93         if formset.is_valid():
 94             formset.save()
 95             url = reverse('event_tickets_summary', args=[event_slug, cart_id])
 96             return redirect(url)
 97             
 98     else:
 99         initial =[]
100         for item in cart_items:
101             for i in range(1, item.quantity+1):
102                 initial.append({'item':item.item})
103         formset = ItemUserDetailsFormset(initial=initial)
104         
105     template = 'payments/user_details.html'
106     template_vars = {'event':event, 
107                      'cart': cart, 
108                      'formset': formset}
109     return render(request, template, template_vars)

0 个答案:

没有答案