我有这个表单,你输入一个用户名到charfield,模型如下:
models.py
class Message(models.Model):
sender = models.ForeignKey(User)
receiver = models.ForeignKey(User)
message = models.CharField(max_length=255)
forms.py
class MessageForm(forms.ModelForm):
sender = forms.CharField(widget=forms.HiddenInput)
receiver = forms.CharField(max_length=255)
message = forms.CharField(widget=forms.Textarea)
class Meta:
model = Message
fields = ['sender', 'receiver', 'message']
labels = {
'receiver': 'Message to',
}
错误
Exception Type: ValueError
Exception Value:
Cannot assign "'testuser'": "Message.receiver" must be a "User" instance.
所以基本上我希望用户将用户名输入到CharField中,但它显然抱怨该字段不接受文本,因为它只接受用户实例。最好的方法是什么?我正在考虑覆盖save()
或post()
来传递字段中的文本并从查询集中获取用户(User.objects.get(username=receiver)
),但我不确定如何实现这个。有人有这个建议吗?感谢所有帮助!
答案 0 :(得分:0)
尝试在表单中添加另一个字段以输入用户名并将sender字段设置为隐藏输入,同时验证表单使用clean_sender方法将发件人设置为User实例:
class Message(models.Model):
sender = models.ForeignKey(User)
receiver = models.ForeignKey(User)
message = models.CharField(max_length=255)
在forms.py中:
class MessageForm(forms.ModelForm):
sender = forms.HiddenInput()
receiver = forms.HiddenInput()
message = forms.CharField(widget=forms.Textarea)
sender_username = forms.CharField(max_length =255, verbose_name = "Sender")
receiver_username = forms.CharField(max_length =255, verbose_name = "Receiver")
class Meta:
model = Message
fields = '__all__'
labels = {
'receiver': 'Message to',
}
def clean_sender(self):
return User.objects.get(username=self.cleaned_data.get('sender_username'))
def clean_sender(self):
return User.objects.get(username=self.cleaned_data.get('receiver_username'))
通过添加其他字段,您可以将用户名作为输入,然后在验证表单时获取相应的用户实例。
Here是保存前清除表单中单个字段的链接。