Access instance passed to ModelForm from clean(self) method
23,537
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
Related videos on Youtube
Author by
epalm
Updated on July 09, 2022Comments
-
epalm over 1 year
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 ofif (first == second)
? -
epalm over 12 yearsOops,
self.instance.first
seems to work after restarting the dev server. Thanks! -
Yuji 'Tomita' Tomita over 12 yearsI have no idea why you would get a
DoesNotExist
: that is the most curious part -- you should post your whole traceback on that error.