开发者

Access instance passed to ModelForm from clean(self) method

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

c开发者_StackOverflow中文版lass 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))

A logged-in user wants to pair up with another user. They are shown a form with a dropdown. If they choose themselves, raise a validation error.

Question: in PairForm's clean(self) method, how can I access the user I set on the Pair which I gave to the PairForm?

Bonus question: should that be if (first is second) instead of if (first == second)?


In a ModelForm, the instance is accessible via self.instance

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜