12
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))
登錄的用戶想要與另一個用戶配對。它們以下拉列表形式顯示。如果他們選擇自己,提出驗證錯誤。從clean(self)方法傳遞給ModelForm的訪問實例
問題:在PairForm的clean(self)
方法中,如何訪問我在Pair上設置的用戶,並將其添加到PairForm中?
獎勵問題:應該是if (first is second)
而不是if (first == second)
?
權是可訪問的,我試過了,最初並得到了DoesNotExist錯誤。 – epalm 2011-02-26 20:16:23
糟糕,'self.instance.first'似乎在重新啓動dev服務器後工作。謝謝! – epalm 2011-02-26 20:36:24
我不知道爲什麼你會得到一個'DoesNotExist':這是最奇怪的部分 - 你應該發佈你的整個回溯的錯誤。 – 2011-02-26 20:37:01