0

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

user683742
  • 80
  • 2
  • 8

1 Answers1

0

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

user1614526
  • 474
  • 1
  • 4
  • 13