I created a project with Django and am trying to write from forms to db. The model class has two classes :
class Contact(models.Model):
name = models.CharField(max_length=200)
birth_day = models.DateTimeField()
address = models.CharField(max_length=200)
class PhoneNumber(models.Model):
PHONETYPE_CHOICES = (
(0, 'Home'),
(1, 'Work'),
(2, 'Fax'),
(3, 'Mobile'),
(4, 'Other'),
)
contact = models.ForeignKey(Contact)
phone_type = models.CharField(max_length=255, choices=PHONETYPE_CHOICES)
phonenumber = models.CharField(max_length=30)
Now if I want to write to this with forms and I use only:
Name
Birthday
Address
Number type
Phone Number
as form fields.
I get:
IntegrityError x_phonenumber.contact_id may not be NULL
This is part of the view:
def main(request):
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name'],
birth_day = form.cleaned_data['birth_day'],
address = form.cleaned_data['address'],
# contact1= form.cleaned_data['id']
phone_type = form.cleaned_data['phone_type']
phonenumber = form.cleaned_data['phonenumber']
contact = Contact(
name = form.cleaned_data['name'],
birth_day = form.cleaned_data['birth_day'],
address = form.cleaned_data['address'],
)
contact.save()
number = PhoneNumber(
# contact1 = form.cleaned_data ['id']
phone_type = form.cleaned_data['phone_type'],
phonenumber = form.cleaned_data['phonenumber'],
)
number.save()
I know I have to fill in the ID of the person in that ForeignKey, but I thought that is what the ForeignKey will do for me.
The two commented out object "contact1" did not work. But that is basically what I want, add the id to this.
Also, Django always adds an _id primary key to every table (contact and Phonenumber).
So i did not get why, Django did not add to this.
How can I save this to db with the correct id, primary key etc..
Thanks