Home > Mobile >  How to exclude a field but save its data?
How to exclude a field but save its data?

Time:08-31

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

CodePudding user response:

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})

CodePudding user response:

you need to 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.

  • Related