I'm trying to submit two forms within one view. First, a user shares a URL through the first form. My program then renders some graphs and will ask the user at the end of the page to fill out a form and submit it. Here's how I'm trying to solve it:
views.py:
if request == "POST":
if 'first-input-name' in request.POST: # or in request.POST.get('name')
# do something
elseif 'second-input-name' in request.POST: # or in request.POST.get('name')
# do something else
template:
<input type="submit" name="first-input-name"/>
<input type="submit" name="second-input-name"/>
This is the approach I found in answers to similar questions. However, in my requests.POST
I don't find the name of my input, and therefore I don't get the expected behavior.
Any ideas on how to solve this?
CodePudding user response:
I recommend a better and less difficult approach, that is to create different action urls with related functions:
In template:
<form action="{% url 'view-1' %}">
<input type="submit" name="first-input-name"/>
# other...
</form>
<form action="{% url 'view-2' %}">
<input type="submit" name="second-input-name"/>
# other...
</form>
In urls:
path(first/, first_view, name="view-1"),
path(second/, second_view, name="view-2"),
In views:
def first_view(request):
if request.method == "POST":
#do something...
def second_view(request):
if request.method == "POST":
#do something...
CodePudding user response:
You can just have one form with two fields to reduce code complexity. And do the below
def single_view(request):
if request.method == "POST":
# i also advice you use underscore(AKA snake_case) instead of hyphens
first_input_name = request.POST.get("first_input_name")
second_input_name = request.POST.get("second_input_name")
This also mean in your inputs you will have value="first_input_name"
and value="second_input_name"
in your inputs