如果已經在另一個問題中涉及到此問題,我表示歉意 - 我是Django的新手,可能一直盯着此問題以及有關Stack的許多其他問題,現在有點太長了..在ModelForm字段中過濾模型實例
使用Django 1.8.2,我有一個模型,它顯示了一個用戶列表,我想從中排除當前用戶(即你看不到你自己)。我試圖通過覆蓋init方法來從「to_user」列表中排除當前用戶。我得到下面的錯誤(「邀請沒有to_user」),我不明白。不應該從模型中的to_user ForeignKey字段填充字段?
您的幫助和時間都非常讚賞 -
特定的錯誤是:
我模式是:
class Invitation(models.Model):
from_user = models.ForeignKey(User, related_name="invitations_sent")
to_user = models.ForeignKey(User, related_name="invitations_received", verbose_name="User to Invite", help_text="This is Help Text") # Verbose name is the form label for Foreigh Key vars
message = models.CharField("Optional Message", max_length=300, blank=True) # Can add string for lavel, Setting blank=True means the field won't be required with ModelForm
timestamp = models.DateTimeField(auto_now_add=True)
我窗體類是:
class InvitationForm(ModelForm):
class Meta: # Class Meta sets the model class that the form needs to be auto-created for
model = Invitation
exclude = ['from_user']
def __init__(self, user, **kwargs):
super(InvitationForm, self).__init__(user, **kwargs)
self.fields['to_user'].queryset = Invitation.objects.exclude(user=self.instance.to_user)
我觀點是:
@login_required
def new_invitation(request):
if request.method == "POST":
invitation = Invitation(from_user=request.user)
form = InvitationForm(data=request.POST, instance=invitation)
if form.is_valid():
form.save()
return redirect('user_home')
else:
form = InvitationForm(user=request.user)
return render(request, "tictactoe/new_invitation.html", {'form' : form})
異常提到'Invitation'對象沒有'to_user'設置(該字段爲空) – karthikr
感謝您的幫助,karthikr。 –