click here
click here

Reputation: 836

Handling two forms in the same view

I have the following stripped function.

def jobs(request):
    pms = PM.objects.all()
    a = Job.objects.all().filter(enddate__gte=datetime.date.today()).order_by('enddate')
    ljform = LaunchJobForm(request.POST or None)
    form = LimitedJobForm(request.POST or None, prefix='add')
    if request.method=='POST' and 'addjobbtn' in request.POST:
      if form.is_valid():
       ...do stuff...
    elif request.method=='POST' and 'launchjobbtn' in request.POST:
      print('test')
      ... do other stuff...

My ljform is

<form method='POST' action = '' class='launchjob'>{% csrf_token %}
    {{ ljform }}
    <td><button class = 'btn btn-primary' name='launchjobbtn' type='submit'>Launch Job</button></td>
    <td><input id='emailcheck' type="checkbox">Modify Email</input></td>
</form>

My addjob form is:

<div class='jobfrm{% if form.errors %} has_errors{% endif %}'>
    <span class='closex' >&#10006;</span>
    <form method='POST' action = '' class='addjob'>{% csrf_token %}
        {{form|crispy}}
        <input class = 'btn btn-default' name='addjobbtn' type = 'submit' value = 'Submit'/>
    </form> 
</div>  

My problem is that when I click the launch job button form validation errors are triggered on the jobfrm. It doesn't actually take that if path. It does take the elif path and prints 'test'. But I cannot figure out why it's triggering the other form.

Upvotes: 2

Views: 46

Answers (1)

gtlambert
gtlambert

Reputation: 11971

You only want to pass request.POST as an argument to your form if that is the form that has been submitted. This means you have to do something like this:

def jobs(request):

    pms = PM.objects.all()
    a = Job.objects.all().filter(enddate__gte=datetime.date.today()).order_by('enddate')

    ljform = LaunchJobForm()
    form = LimitedJobForm()

    if request.method=='POST' and 'addjobbtn' in request.POST:
        form = LimitedJobForm(request.POST)          
        if form.is_valid():
         ...do stuff...

    elif request.method=='POST' and 'launchjobbtn' in request.POST:
        ljform = LaunchJobForm(request.POST)
        print('test')
        ... do other stuff...

Upvotes: 3

Related Questions