Django限制了多对多关系的选择

时间:2017-05-14 06:01:17

标签: python django django-views

我知道标题说之前已经提出了问题,但情况有所不同。

我有一个名为Agent的东西:

class Agent(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='agents')
    ...

Group

class Group(models.Model):
    agents = models.ManyToManyField('agents.Agent', blank=True, related_name='groups')

现在使用基于Django类的视图(可能是UpdateView)我想创建一个视图,用户可以看到只有其代理只选择一个将其添加到特定群组。

据我所知是

@method_decorator(login_required, name='dispatch')
class GroupAgentRegister(UpdateView):
    model = Group
    fields = ('agents',)
    template_name = 'register.html'
    context_object_name = 'group'

    def get_form(self, form_class=None):
        form = super(GroupAgentRegister, self).get_form(form_class)
        form.fields['agents'].queryset = self.request.user.agents.all()
        return form

    def form_valid(self, form):
        if self.object.agents.filter(user=self.request.user):
            form.add_error(None, ValidationError(u'Already Registered'))
            return super(GroupAgentRegister, self).form_invalid(form)
        return super(GroupAgentRegister, self).form_valid(form)

表单呈现很好,除了我能够选择多个代理。 但是当我选择一个值并发布它时,它会用现有的代理替换新选择的代理,并且它不会附加到旧的代理上。

1 个答案:

答案 0 :(得分:0)

我这样解决了。它也可以帮助别人。

首先我创建了一个表单:

class GroupRegistrationForm(forms.ModelForm):
    agents = forms.ModelChoiceField(Group.objects.none())

    class Meta:
        model = Group
        fields = ('agents',)

我将注册视图更改为:

@method_decorator(login_required, name='dispatch')
class GroupAgentRegister(UpdateView):
    model = Group
    form_class = GroupRegistrationForm
    fields = ('agents',)
    template_name = 'register.html'
    context_object_name = 'group'

    def get_form(self, form_class=None):
        form = super(GroupAgentRegister, self).get_form(form_class)
        form.fields['agents'].queryset = self.request.user.agents.all()
        return form

    def form_valid(self, form):
        if self.object.agents.filter(user=self.request.user):
            form.add_error(None, ValidationError(u'Already Registered'))
            return super(GroupAgentRegister, self).form_invalid(form)
        self.object.agents.add(form.cleaned_data['agents'])
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())

并且一切正常,我必须应用最小的变化。