如果你现在使用save方法,Django将尝试使用管理器(Django不允许)进行保存.不幸的是,你想要的行为比ModelForm
默认情况下有点棘手.您需要做的是创建一个formset.
首先,您需要更改您的选项,ClientForm
以便它不显示该groupes
属性.
class ClientForm(ModelForm): class Meta: model = Client exclude = ('groupes',)
接下来,您必须更改视图以显示formset:
from django.forms.models import inlineformset_factory def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) # Create the formset class GroupeFormset = inlineformset_factory(Client, Groupe) # Create the formset formset = GroupeFormset(instance = client) dict = { "form": form , "formset" : formset , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) formset = GroupeFormset(request.POST, instance = client) if form.is_valid() and formset.is_valid(): client_mod = form.save() formset.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) )
显然,您还必须调整模板以呈现formset.
如果您需要有关formset的任何其他建议,请参阅以下文章:
模型formsets
Formsets
如果你现在使用save方法,Django将尝试使用管理器(Django不允许)进行保存.不幸的是,你想要的行为比ModelForm
默认情况下有点棘手.您需要做的是创建一个formset.
首先,您需要更改您的选项,ClientForm
以便它不显示该groupes
属性.
class ClientForm(ModelForm): class Meta: model = Client exclude = ('groupes',)
接下来,您必须更改视图以显示formset:
from django.forms.models import inlineformset_factory def modifier(request, id): client = Client.objects.get(id=id) form = ClientForm(instance = client) # Create the formset class GroupeFormset = inlineformset_factory(Client, Groupe) # Create the formset formset = GroupeFormset(instance = client) dict = { "form": form , "formset" : formset , "instance" : client } if request.method == "POST": form = ClientForm(request.POST, instance = client) formset = GroupeFormset(request.POST, instance = client) if form.is_valid() and formset.is_valid(): client_mod = form.save() formset.save() id = client_mod.id return HttpResponseRedirect( "/client/%(id)s/?err=success" % {"id" : id} ) else: return HttpResponseRedirect( "/client/%(id)s/?err=warning" % {"id" : id} ) return render_to_response( "client/modifier.html" , dict , context_instance=RequestContext(request) )
显然,您还必须调整模板以呈现formset.
如果您需要有关formset的任何其他建议,请参阅以下文章:
模型formsets
Formsets
… if form.is_valid(): client_mod = form.save(commit=False) client_mod.save() for groupe in form.cleaned_data.get('groupes'): clientgroupe = ClientGroupe(client=client_mod, groupe=groupe) clientgroupe.save() …