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" >Update Profile</button>
</form>
<form action="" method="POST">
{% csrf_token %}
{{addaccount_form}}
<button type="submit" >Add Account</button>
</form>
CodePudding user response:
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/")
CodePudding user response:
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!