Issue
I creating an app to keep pets info. I'm displaying a form to insert data with a user profile. I don't want to display the parent option because that should be saved automatically but have no idea how to do that. If I exclude the parent, in the form doesn't appear but the pet's info is not linked to the user.
forms.py:
class PetForm(ModelForm):
class Meta:
model = Pet
exclude = ('parent',)
models.py:
class Pet(models.Model):
pet_name = models.CharField(max_length=200)
parent = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True)
def __str__(self):
return self.pet_name
Solution
you need to add this in your view.
form = PetForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.parent = parent
instance.save()
of course you should specify parent object too.
Answered By - hiwa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.