这是我的示例模型:
class Booking(models.Model):
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=256)
last_name = models.CharField(max_length=256)
class MailList(models.Model):
email = models.EmailField(unique=True)
booking = models.ForeignKey(Booking, blank=True, null=True)
我有一个表单,我已经将 FK 字段修改为 CharField。我的代码去:
表格.py
class MailListAdminForm(forms.ModelForm):
booking= forms.CharField(required=False)
class Meta:
model = MailList
def clean_myfield(self):
data = self.cleaned_data['booking']
try:
self.booking= Booking.objects.get(pk=data)
return data
except (KeyError, Booking.DoesNotExist):
raise forms.ValidationError('Invalid Booking ID. Please try again.')
管理员.py
class MailListAdmin(admin.ModelAdmin):
form = mailListAdminForm
我收到一个错误,“Django 版本:1.3.1
异常类型:ValueError
无法分配“u'143590'”:“MailList.booking”必须是“Booking”实例。”
知道如何解决这个问题吗?谢谢