0

If the python function "is_valid" has an exception, how do I keep the input values that were entered on the django form? I did search, maybe I don't know a better way to search. If there is a better way to use a Parent Child model, please tell me.

First I save the Parent model, then save the Child model in same view.

On exception, I want to rollback Parent and redirect user back to the same page with the fields populated with their values.

I have combined 2 forms, each uses a different model. I'm using class-based views.

The line below "_starting", (print(forms), gives me:

{'parent_form': <Parent_2testForm bound=True, valid=True, fields=(title_test;modelname_id)>, 'child_form': <Child_testForm bound=True, valid=True, fields=(content_test)>}

urls.py path('newpos/parent2',views.Parent2.as_view(),name='parent2'),

Models.py

class Parent_test(models.Model):
    title_test = models.CharField(max_length=50)
    modelname_id = models.IntegerField(null=False, default=0, unique=False)

class Child_test(models.Model):
    content_test = models.TextField()
    id_key = models.IntegerField(null=False, default=0, unique=False)
    parent_test = models.ForeignKey(Parent_test, on_delete=models.CASCADE)

forms.py


class Parent_2testForm(ModelForm):
    class Meta:
        model = Parent_test
        fields = ('title_test', 'modelname_id', )
        widgets = {
            'modelname_id': forms.TextInput(attrs={'type': 'hidden'}),
        }

class Child_testForm(ModelForm):
    class Meta:
        model = Child_test
        fields = ('content_test',)

Views.py

class Parent2(MultiModelFormView):
   form_classes = {
       'parent_form': Parent_2testForm,
       'child_form': Child_testForm,
   }
   def __init__(self, title_test="", content_test="", *args, **kwargs):
       self.title_test = title_test
       self.content_test = content_test

   template_name = 'newpos/parent2.html'
   def get_success_url(self):
       return reverse('new_purchase_order')

   def forms_valid(self, forms):
       print("__c_inside_Parent2_forms_valid")

       try:
          with transaction.atomic():
              print("_______starting______")
              print(forms)

              parentsave = forms['parent_form'].save()
              parentsave.modelname_id = parentsave.id

              Parent_test.objects.update_or_create(id=parentsave.id, defaults={'modelname_id': parentsave.id})

              child2 = forms['child_form'].save(commit=False)
              child2.parent_test_id = parentsave.id

              child2.id_key = parentsave.id

              child3 = child2
              child3.save()

       except ValueError as e:
            amsg = "__ValueERROR_exception_" + str(e)

            # raise # to remove record saved in Parent
            context = {}
            messages.error(self.request, amsg)
            return HttpResponseRedirect(self.request.path_info)

       except Exception as e:
          amsg = "__ERROR_exception_" + str(e)
          # raise  # to remove record saved in Parent
          messages.error(self.request, amsg)
          return HttpResponseRedirect(self.request.path_info )

       return super(Parent2, self).forms_valid(forms)

I want to send the input values back in the form.

I have tried "request" option, but that did not work.

3
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. Commented Jun 11, 2024 at 6:10
  • I want the exception to return the input values. Example for title, User types in "Mary had a Little Lamb". User does "Submit". In Python, it goes into the Exception module. I want the the Exception to stay on same page with the words "Mary had a Little Lamb" as title. Currently it stays on same page, however the title is BLANK. Commented Jun 11, 2024 at 12:43
  • I SOLVED it myself. I got a lot of info from: stackoverflow.com/questions/6276398/… Commented Jun 14, 2024 at 12:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.