2013-10-31 54 views
-1

我传递的表单如更新ManyToManyField在Django从表格数据

form = GuestForm(request.POST) 
if form.is_valid(): 
    full_name = form.cleaned_data['full_name'] 
    street_address = form.cleaned_data['street_address'] 
    city = form.cleaned_data['city'] 
    state = form.cleaned_data['state'] 
    zip_code = form.cleaned_data['zip_code'] 
    guests = form.cleaned_data['guests'] 
    children = form.cleaned_data['children'] 
    email = form.cleaned_data['email'] 
    phone_number = form.cleaned_data['phone_number'] 
    gift_description = form.cleaned_data['gift_description'] 
    status = form.cleaned_data['status'] 

    guest = Guest.objects.filter(id=guest_id).update(user=request.user, 
     full_name=full_name, street_address=street_address, city=city, 
     state=state, zip_code=zip_code, guests=guests, children=children, 
     email=email, phone_number=phone_number, gift_description=gift_description, 
     status=status) # The status is clearly not updated 

我怎样才能做到这一点?

编辑

GuestForm

class GuestForm(ModelForm): 
    status = forms.ModelMultipleChoiceField(
     queryset=GuestStatus.objects.all().order_by('arrangement'), 
     widget=forms.CheckboxSelectMultiple, required=False) 

    class Meta: 
     model = Guest 
     exclude = ['user', 'invitation_date'] 
+0

向我们显示'GuestForm' – Rohan

+0

更新的公猪!!! – pynovice

回答

1

参考modelForm文档,当您使用modelForms你并不需要这么多的代码,你的代码将减少到:

guest = get_object_or_404(Guest, id=guest_id) 
form = GuestForm(instance=guest) 

再次发帖,

#get the guest instance, if updating existing record 
form = GuestForm(request.POST, instance=guest) 
if form.is_valid(): 
    new_guest = form.save(commit=False) #you want to set excluded fields 
    new_guest.user = request.user 
    #new_guest.invitation_date = somedate 
    new_guest.save() 
    form.save_m2m() #should do this if save(commit=False) used 
+0

我正在尝试更新该字段。但是我得到这个错误:''Guest'对象没有'save_m2m'' – pynovice

+0

@ user2032220属性,对不起,它应该是'form.save_m2m()'。 – Rohan