This is my sample model:
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)
I have a form, I already modify the FK field to become a CharField. my code goes to:
form.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.')
admin.py
class MailListAdmin(admin.ModelAdmin):
form = mailListAdminForm
I got an error, "Django Version: 1.3.1
Exception Type: ValueError
Cannot assign "u'143590'": "MailList.booking" must be a "Booking" instance."
any idea how to solve this problem? Thanks
If i understood your question
Then you are getting this error because
in your views you are trying to store a value with MailList.booking
the attribute booking is the FK to table Booking so
you can't store a value with that you have to pass the object of Booking table
for MailList.booking
like
`MailList.booking` = bookingobject
bookingobject
should be the instance of your Booking table
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.