Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access instance passed to ModelForm from clean(self) method

Tags:

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))

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)?

like image 663
epalm Avatar asked Feb 26 '11 20:02

epalm


1 Answers

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

like image 162
Yuji 'Tomita' Tomita Avatar answered Sep 21 '22 19:09

Yuji 'Tomita' Tomita