I have 3 form inputs that will be submitted when one master button is clicked to then be passed into a view as the request parameter. I would like to get the values of first_name, last_name and email inside my view using request.get(). When the button is clicked the values inside my form appear as None
HTML:
<div id="form_content">
<form action="" method="post">
<section >
<label for="first_name">First Name:</label>
<input type="text" id="first_name">
</section>
<section >
<label for="last_name">Last Name:</label>
<input type="text" id="last_name">
</section>
<section >
<label for="email">Email:</label>
<input type="text" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
views.py
def home(request):
form_response = request.GET.get("form_content")
print(form_response)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)
CodePudding user response:
In your input tags, you have not passed the name
parameter. Pass the name
parameter in our input tags as django collects the data from the name tags. For example in your case, it must be:
<input type="text" id="id_first_name" name="first_name">
<input type="text" id="id_last_name" name="last_name">
<input type="text" id="id_email" name="email">
CodePudding user response:
first you need to add csrf_token in your code for post method and also give a name for each input like this :
<div id="form_content">
<form action="" method="post">
{% csrf_token %}
<section >
<label for="first_name">First Name:</label>
<input type="text" name="first_name" id="first_name">
</section>
<section >
<label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="last_name">
</section>
<section >
<label for="email">Email:</label>
<input type="text" name="email" id="email">
</section>
<input type="submit" value="Submit">
</form>
</div>
and then:
def home(request):
first_name = request.POST['first_name']
last_name = request.POST['last_name']
email = request.POST['email']
print(first_name, last_name, email)
context = {"title": "Home"}
return render(request, "myApp/home.html", context)