Hi Jarvis,

The code which you have posted only shows the model. Within your cat and 
dog models the owner can be null. Which explains why the owner is not 
associated with the pets. Can I see the code you tried to insert the 
records?

## changes needed in models
models.ForeignKey(Owner, related_name='cats', on_delete=models.CASCADE)
models.ForeignKey(Owner, related_name='dogs', on_delete=models.CASCADE)

## code for inserting records
owner = Owner.objects.create_user(username="blah", password="blah", 
email="b...@blah.com")
dog = Dog(name="mydog", bday=datetime.today(), owner=owner).save()


Thanks.

On Sunday, 28 January 2018 07:10:31 UTC+5:30, tangoward15 wrote:
>
>
> Hi,
>
> I am playing around with CRUD. I want a user a create an account first 
> before he/she can add pets under his/her profile. I tried adding one pet 
> however it's seems that it is not associated to the Owner who added the pet.
>
> models.py
>
> from django.db import models
> from django.contrib.auth.models import User, PermissionsMixin
> from django.urls import reverse
> # Create your models here.
>
>
> class Owner(User, PermissionsMixin):
>
>     def __str__(self):
>         return self.username
>
>
> class Cat(models.Model):
>     name = models.CharField(max_length=40)
>     bday = models.DateField()
>     owner = models.ForeignKey(Owner, related_name='cats', null=True, 
> on_delete=models.SET_NULL)
>
>     def get_absolute_url(self):
>         return reverse('test')
>
>     def __str__(self):
>         return self.name
>
>
> class Dog(models.Model):
>     name = models.CharField(max_length=40)
>     bday = models.DateField()
>     owner = models.ForeignKey(Owner, related_name='dogs', null=True, 
> on_delete=models.SET_NULL)
>
>     def get_absolute_url(self):
>         return reverse('test')
>
>     def __str__(self):
>         return self.name
>
>
> Any suggestions will be highly appreciated.
>
>
> Regards,
> Jarvis
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/8f31afb0-2a9d-49ef-94b4-213aef140cf2%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to