在Django中使ModelForm与ManyToMany关系与中间模型一起工作的步骤是什么?

bch*_*hun 30 python django django-templates django-models django-forms

  • 我有一个客户端和Groupe模型.
  • 一个客户端可以是多个的一部分群体.
  • 属于某个群组的客户可以随时使用其群组的免费租赁费率,但只能使用一次.这就是中间模型(ClientGroupe)带来额外数据的地方.

现在,当我尝试保存m2m数据时,它就死了,并说我应该使用ClientGroupe Manager ...那么缺少什么?

这是我的模特:

class Groupe(models.Model):
    nom = models.CharField(max_length=1500, blank=True)

class Client(models.Model):
    nom = models.CharField(max_length=450, blank=True)
    prenom = models.CharField(max_length=450, blank=True)
    groupes = models.ManyToManyField(Groupe, null = True, blank = True, through='ClientGroupe')

class ClientGroupe(models.Model):
    client = models.ForeignKey(Client)
    groupe = models.ForeignKey(Groupe)
    dt = models.DateField(null=True, blank=True) # the date the client is using its group's free rental rate    

    class Meta:
        db_table = u'clients_groupes'
Run Code Online (Sandbox Code Playgroud)

这是我的看法:

def modifier(request, id):
    client = Client.objects.get(id=id)    
    form = ClientForm(instance = client)

    dict = {
        "form": form
        , "instance" : client
    }

    if request.method == "POST":
        form = ClientForm(request.POST, instance = client)

        if form.is_valid():
            client_mod = form.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)
    )
Run Code Online (Sandbox Code Playgroud)

编辑:

这是ClientForm代码:

class ClientForm(ModelForm):
    class Meta:
        model = Client
Run Code Online (Sandbox Code Playgroud)

编辑#2:这是错误信息:

AttributeError at /client/445/

Cannot set values on a ManyToManyField which specifies an intermediary model. Use ClientGroupe's Manager instead.

Request Method:     POST
Request URL:    http://localhost/client/445/
Exception Type:     AttributeError
Exception Value:    Cannot set values on a ManyToManyField which specifies an intermediary model.  Use ClientGroupe's Manager instead.

Exception Location:     C:\Python25\lib\site-packages\django\db\models\fields\related.py  in __set__, line 574
Python Executable:  C:\xampp\apache\bin\apache.exe
Python Version:     2.5.2
Run Code Online (Sandbox Code Playgroud)

Ros*_*ght 18

如果你现在使用save方法,Django将尝试使用管理器(Django不允许)进行保存.不幸的是,你想要的行为比ModelForm默认情况下有点棘手.您需要做的是创建一个formset.

首先,您需要更改您的选项,ClientForm以便它不显示该groupes属性.

class ClientForm(ModelForm):
    class Meta:
        model = Client
        exclude = ('groupes',)
Run Code Online (Sandbox Code Playgroud)

接下来,您必须更改视图以显示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)
    )
Run Code Online (Sandbox Code Playgroud)

显然,您还必须调整模板以呈现formset.

如果您需要有关formset的任何其他建议,请参阅以下文章:

模型formsets
Formsets

  • 是的,那实际上并不奏效.inlineformset_factory需要一个ForeignKey (4认同)

Anb*_*ber 10

…
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()
    …
Run Code Online (Sandbox Code Playgroud)

  • 不要忘记删除db中存在但不在clean_data中的ClientGroupe实例,并且不要忘记在此表单中保存其他m2m字段.而且,我更喜欢将它放在ClientForm.save()方法中. (5认同)