Access实例从clean(self)方法传递给ModelForm

时间:2011-02-26 20:03:21

标签: django django-models django-forms

class Pair(models.Model):
    first = models.ForeignKey(User, related_name='pair_first')
    second = models.ForeignKey(User, related_name='pair_second')

class PairForm(forms.ModelForm):
    class Meta:
        model = Pair
        fields = ('second',)

    def clean(self):
        first = None # how can I get first?
        second = self.cleaned_data.get("second")

        if (first == second):
            raise ValidationError("You can't pair with yourself, silly.")

def pair_create(request):
    if request.method == 'POST':
        pair = Pair()
        pair.first = request.user
        form = PairForm(instance=pair, data=request.POST)
        if form.is_valid():
            form.save();
            return HttpResponseRedirect(reverse('somewhere'))
    else:
        form = PairForm()

    return render_to_response('something.html', {
        'form': form,
    }, context_instance=RequestContext(request))

登录用户希望与其他用户配对。它们显示为带下拉列表的表单。如果他们自己选择,则提出验证错误。

问题:在PairForm的clean(self)方法中,如何访问我在PairForm上设置的用户?

加分问题:应该是if (first is second)而不是if (first == second)吗?

1 个答案:

答案 0 :(得分:35)

ModelForm中,可以通过self.instance

访问该实例

self.instance.first == self.cleaned_data.get("second")

http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method