0

I want to display both form1 and form2 on a web page. If form2 is filled (if success == True), I want my view to not execute if form1.is_valid:

(which gives errors). How can I access the value of success in views.py?

forms.py

class Form1(forms.Form):
    ....
    ....
    def clean(self):
        ....
        ....

class Form2(forms.Form):
    ....
    ....
    def clean(self):
        ....
        success = False

views.py

def my_view(request, element_pk):
    ....
    ....
    if request.method == POST:
        form2 = Form2(request.POST)
        form1 = Form1(request.POST)

    if form2.is_valid():
        ....
    if form1.is_valid():
        ....

    else:
        form2 = Form2()
        form1 = Form1()
eager_coder
  • 47
  • 1
  • 8
  • You may need to take a look of the answers on [this question](http://stackoverflow.com/questions/1395807/proper-way-to-handle-multiple-forms-on-one-page-in-django). – Abz Rockers Aug 30 '16 at 01:27
  • @AbzRockers There is only one Submit button in the template file that my view renders. – eager_coder Aug 30 '16 at 01:48

2 Answers2

0

For your <input /> or <button></button> tag, use a name parameter for each form (i.e.):

<button type="submit" name="form_1">Go!</button>

Then, in your view, do something like:

if form2.is_valid() and 'form_2' in request.POST:
    . . .
if form1.is_valid() and 'form_1' in request.POST:
    . . .
jape
  • 2,591
  • 2
  • 17
  • 52
0

Setting success = False as you've done in the clean method only sets it locally. Store the value on the class (self.success = False) or in the cleaned_data (self.cleaned_data['success'] = False, assuming your form has no field called success).

Then, you can access the value with:

if form2.is_valid():
    success = form2.success

or

if form2.is_valid():
    success = form2.cleaned_data.get('success')

For more information about the clean function, see the docs.

jamjar
  • 545
  • 3
  • 10