tiberhockey
tiberhockey

Reputation: 576

Django Multiple Form on same page interact with each other

I have a page with two forms. When I click on the button Update Profile on the left Form it also send the POST request to the the second form which is not what I want. I don't want them to interact together. How can I do that?

views.py

@login_required(login_url='signin')
def dashboard(request):
    global user_id

    data = Account.objects.filter(user=request.user)

    profile_data = Profile.objects.get(user=request.user)

    profile_form = ProfileForm(request.POST or None, instance=profile_data)
    addaccount_form = AddAccountForm(request.POST or None)

    # Update Profile Settings
    if profile_form.is_valid():
        print("worked")
        profile_form.save()

    if request.method == "POST":
        if addaccount_form.is_valid():
            # save account to DataBase

            return HttpResponseRedirect("http://127.0.0.1:7000/dashboard/")

    context = {
        'data': data,
        'profile_form': profile_form,
        'addaccount_form': addaccount_form,

    }

    return render(request, "main/dashboard.html", context)

dashboard.html

<form action="" method="POST">
        {% csrf_token %}
        {{profile_form}}
        <button type="submit" class="updatebut">Update Profile</button>
</form>

<form action="" method="POST">
        {% csrf_token %}
        {{addaccount_form}}
        <button type="submit" class="addbut">Add Account</button>
</form>

Upvotes: 1

Views: 295

Answers (2)

Ali Kocak
Ali Kocak

Reputation: 62

You can check which form in your request

if 'profile_form' in request.POST:
    profile_form = ProfileForm(request.POST or None, instance=profile_data)
    if profile_form.is_valid():
        print("worked")
        profile_form.save()
elif 'addaccount_form' in request.POST:
    addaccount_form = AddAccountForm(request.POST or None)
    if addaccount_form.is_valid():
        # save account to DataBase
        return HttpResponseRedirect("http://127.0.0.1:7000/dashboard/")

Upvotes: 1

johnster000
johnster000

Reputation: 51

You can add a name to each one of your submit buttons (ex. name="addaccount" and name="updateprofile")

And in your view, add the following:

if 'addaccount' in request.POST: ---do the addacount elif 'updateprofile' in request.POST: ---do the profile update

Quick and dirty!

Upvotes: 1

Related Questions