How to exclude a field but save its data?

Question:

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
Asked By: Xiomara Canizales

||

Answers:

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

Yes, you can work with commit=False while saving in the form in POST method, see an example below.

Try this view:

views.py

def some_view_name(request):
    if request.method=="POST":
        form = PetForm(request.POST)
        if form.is_valid():
           pet = form.save(commit=False)
           pet.parent = request.user.profile.id
           pet.save()
    else:
        form = PetForm()
    return render(request,'any_folder_name/any_file.html',{"form":form})
Answered By: Sunderam Dubey