0

我有一些工作,但我确信这不是最好的方法,因为我有重复的代码。它是一个小部件,用于显示客户端可以属于的组的复选框。一个客户端可以属于多个组。

我确信我以某种方式搞砸了小部件的重载。

模型.py

class Client(models.Model):
    name = models.CharField(u'Name', max_length=250, unique=True)
    groups = models.ManyToManyField('ClientGroup', related_name="client")
    def __unicode__(self):
        return self.name

class ClientGroup(models.Model):
    name = models.CharField(u'Name', max_length=250, unique=True)
    def __unicode__(self):
        return self.name

表格.py

# -*- coding: utf-8 -*-

from django import forms
from models import ClientGroup

class ClientGroupForm(forms.ModelForm):
    class Meta:
        model = ClientGroup
        fields = ('groups',)

    groups = forms.ModelMultipleChoiceField(queryset=ClientGroup.objects.all(),
                                        widget=forms.CheckboxSelectMultiple(),
                                        label='',
                                        required=False)

    def __init__(self, client_id = None, *args, **kwargs):
        super(ClientGroupForm, self).__init__(*args, **kwargs)
        if client_id:
            self.fields['groups'] = forms.ModelMultipleChoiceField(queryset = ClientGroup.objects.all(),
                                        initial=ClientGroup.objects.filter(client = client_id),
                                        widget=forms.CheckboxSelectMultiple(),
                                        label='',
                                        required=False)


    def __unicode__(self):
        return self.groups

视图.py

def client(request, pk = 0):
    client={}
    if pk != 0:
        client = Client.objects.get(pk = pk)

    groupsForm = ClientGroupForm(pk)
    context = {'client':client, 'groupsForm': groupsForm}
    return render(request, 'client.html', context)

谁能告诉我一个更好的forms.py编码方法?

谢谢

4

1 回答 1

0

你可以更换

class ClientGroupForm(forms.ModelForm):
    # stuff

    def __init__(self, client_id = None, *args, **kwargs):
        super(ClientGroupForm, self).__init__(*args, **kwargs)
        if client_id:
            self.fields['groups'] = forms.ModelMultipleChoiceField(queryset = ClientGroup.objects.all(),
                                        initial=ClientGroup.objects.filter(client = client_id),
                                        widget=forms.CheckboxSelectMultiple(),
                                        label='',
                                        required=False)

class ClientGroupForm(forms.ModelForm):
    # stuff

    def __init__(self, *args, **kwargs):
        self.client_id = kwargs.get('client_id', None)
        super(ClientGroupForm, self).__init__(*args, **kwargs)
        if client_id:
            self.fields['groups'].queryset = ClientGroup.objects.filter(client=client_id)
于 2013-04-20T14:39:27.107 回答