0

So I have a CreateView which is using a model form 'A' and I also have a different model which I want to edit when this model inside model form 'A' gets submitted.

How do I access the object when it's not created? Is there any better approach?

Here is the form_valid function()

    def form_valid(self, form):
        member = self.object
        form.instance.registration_upto = form.cleaned_data['registration_date'] + delta.relativedelta(
            months=int(form.cleaned_data['subscription_period']))

        if form.cleaned_data['fee_status'] == 'paid':
            payments = Payments(
                user=member,
                payment_date=form.cleaned_data['registration_date'],
                payment_period=form.cleaned_data['subscription_period'],
                payment_amount=form.cleaned_data['amount'])
            payments.save()
        return super().form_valid(form)

Self.object is None as the object is not yet created. I want to access that object as it's the user in my payments model. I have to stick to class-based views only. Is there a way I can do this?

I'm a little new to Django and looking at the docs didn't help much. Thanks for any advice

Solved

era5tone
  • 579
  • 5
  • 14

1 Answers1

1

You can also do self.object=form.save(commit=False). It will save the object in memory but not commit it to db so you do stuff with that object and after that save the object to db

        if form.cleaned_data['fee_status'] == 'paid':
            payments = Payments(
                user=member,
                payment_date=form.cleaned_data['registration_date'],
                payment_period=form.cleaned_data['subscription_period'],
                payment_amount=form.cleaned_data['amount'])
            # commit false will only save object to memory
            payments.save(commit=False)

            #### Do your stuff here #####

            # regular save will save it to db
            payments.save()
        return super().form_valid(form)
periwinkle
  • 386
  • 3
  • 9