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)
?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With