POST request to Flask Blueprint api not working - python

I am trying to execute a form POST request. The request is received at the route api function but the POST condition is not executing.
Code
<form class="pt-2 pb-4" action = "{{ url_for('data_sources_api.testfn') }}" method = "POST">
<div class="row">
<div class="col-md-4 mb-3">
<label for="url" class="form-label">URL</label>
<input type="text" class="form-control" id="url" name="url" aria-describedby="emailHeurllp"
placeholder="Enter new events top domain source url">
</div>
<div class="col-md-4 mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Organization Name">
</div>
<div class="col-md-12">
<button type="button" class="btn btn-secondary mr-2" value="submit" name = "submit">Submit</button>
</div>
</div>
</form>
Flask Code
#data_sources_api.route('/login/test', methods=["GET", "POST"])
def testfn():
# Check if user is loggedin
if loggedin():
# User is loggedin, render the home page
if request.method == 'POST':
print("POST Request Received")
result = request.form
return render_template('users/data-sources.html', role=session['role'])
return redirect(url_for('account_api.login'))
The request received is GET when i click the submit button and not POST :(
Thanks in advance

I think the problem is with button. Replace the button with input type="submit":
<input type="submit" value="Submit">
Here is the example of Django form.

Related

Value Error when submitting form in Django mysql

I am getting a value error when submitting a form in Django. I have successfully connected the MySQL database in XAMPP. I can not find a solution to this.Here is my form code,
<form class="user" method="POST">
{% csrf_token %}
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Cus_name" name="Cus_name" placeholder="Enter Customer Name...">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Cus_address" name="Cus_address" placeholder="Enter Address... ">
</div>
<div class="form-group">
<input type="email" class="form-control form-control-user" id="Cus_email" placeholder="Enter Email Address...">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Purpose" placeholder="Enter Purpose...">
</div>
<div class="form-group">
<input type="date" class="form-control form-control-user" id="Date" placeholder="Enter Date...">
</div>
<div class="form-group">
<input type="time" class="form-control form-control-user" id="Time" placeholder="Enter Time...">
</div>
<div class="form-group">
<input type="text" class="form-control form-control-user" id="Venue" placeholder="Enter Venue...">
</div>
<button name="submit" type="submit" class="btn btn-success">Submit</button>
<hr>
</form>
Here is my Views.py
from django.shortcuts import render
from .models import AppointmentDet
from django.contrib import messages
def InsertDetails(request):
if request.method == 'POST':
if request.POST.get('Cus_name') and request.POST.get('Cus_address') and request.POST.get('Cus_email') and request.POST.get('Purpose') and request.POST.get('Date') and request.POST.get('Time') and request.POST.get('Venue'):
saverecord = AppointmentDet()
saverecord.Cus_name = request.POST.get('Cus_name')
saverecord.Cus_name = request.POST.get('Cus_address')
saverecord.Cus_name = request.POST.get('Cus_email')
saverecord.Cus_name = request.POST.get('Purpose')
saverecord.Cus_name = request.POST.get('Date')
saverecord.Cus_name = request.POST.get('Time')
saverecord.Cus_name = request.POST.get('Venue')
saverecord.save()
messages.success(request, "details saved successfully!")
return render(request, "appform.html")
else:
return render(request, "appform.html")
Here is the error I am getting when running the server.
ValueError at /
The view Management.views.InsertDetails didn't return an HttpResponse object. It returned None instead.
I tried some solutions but did not work.
You should read this little tutorial on how to work with forms:
https://docs.djangoproject.com/en/3.1/topics/forms/
When the data is sent, you should first cast the post into a form class object. Then you have to call "is_valid()" on said form.
Only after this method call the post data are in the object.
This is the example from django:
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})`

how to access radio button selected value in Django

I am trying to access radio button selected value in my django view but it returns on instead of selected value.
Template form
<form class="col-md-8 mx-auto" action="upload" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group" id="div_id_sample" >
<label for="id_sample" class="col-form-label requiredField">Select File</label><br>
<div class="btn btn-primary">
<input type="file" name="sample" class="clearablefileinput" required id="id_sample" accept=".exe">
</div>
</div>
<div class="form-group">
<label for="radiogroup">Enforce Timeout</label><br>
<div class="btn-group" data-toggle="buttons" id="radiogroup">
<label class="btn btn-secondary">
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60"> 60 seconds
</label>
<label class="btn btn-secondary">
<input type="radio" name="timeoptions" id="option120" autocomplete="off" value="120"> 120 seconds
</label>
<label class="btn btn-secondary active">
<input type="radio" name="timeoptions" id="option180" autocomplete="off" checked value="180"> 180 seconds
</label>
</div>
</div>
<div class="form-group">
<label for="radiogroup2">Select Machine:</label><br>
<div class="btn-group" data-toggle="buttons" id="radiogroup2">
<label class="btn btn-secondary">
<input type="radio" name="machineoptions" id="machine1" autocomplete="off" value="0"> Windows XP
</label>
<label class="btn btn-secondary active">
<input type="radio" name="machineoptions" id="machine2" autocomplete="off" value="1" checked> Windows 7
</label>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
views.py
in my views i am using ModelForm but not in my HTML and the reason behind that is i copied and pasted the htmlcode generated by the ModelForm. Reason is because i need to collect two more items that are not in my data MODEL so that why.
def upload(request):
if request.user.is_authenticated:
if request.method == 'POST':
file = request.FILES['sample']
form = SampleForm(request.POST, request.FILES)
if form.is_valid():
new_sample = form.save(commit=False)
new_sample.file_name = file.name
new_sample.user = request.user
print(request.POST)
TimeOut = request.POST.get('timeoptions')
machine = request.POST.get('machineoptions')
print(TimeOut)
print(machine)
form.save()
return redirect('reports')
else:
messages.info(request,'Invalid Form')
else:
form = SampleForm()
if request.method == 'GET':
return render(request, 'upload2.html', {'form': form})
else:
return redirect(reverse('login'))
Print output
<QueryDict: {'csrfmiddlewaretoken': ['VvAqdOp8RrpKOgwxLD2dpGartPvUrTHTg9AUbqsX6vphxdojTJqn7tsvLCkneWOm'], 'timeoptions': ['on'], 'machineoptions': ['on']}>
on
on
I am just trying to access the selected button value.
I guess this is mostly because you are enclosing the <input> tag inside the <label> tag.Also you must give the for attribute for and put the input element's id in the <label> tag
Try like this:
<label class="btn btn-secondary" for="option60">60 seconds</label>
<input type="radio" name="timeoptions" id="option60" autocomplete="off" value="60">
You can do this for all the radio buttons.Then in your view you can access with TimeOut = request.POST.get('timeoptions')

Problem in getting data from form in flask

I am basically creating a flask web app which takes username from user and gets his /her codeforces data I am having a problem in extracting the email-id
from the form. I am getting the username but not the email-id.They are both in one form tag in the html file.
Error in browser:
werkzeug.exceptions.HTTPException.wrap..newcls: 400 Bad Request: KeyError: 'email-id'
<form method="POST">
<div class="field">
<label class="label">Username:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter Codeforces username" name="username" value="{{user.handle}}"></input>
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-info" type="submit" value="Get Info">
</div>
<div class="field">
<label class="label">EMail id:</label>
<div class="control">
<input class="input" type="text" placeholder="Enter mail id" name="email-id" value="">
</div>
</div>
<div class="has-text-centered">
<input class="button is-link" name="get-mail" type="submit" value="Get Mail">
</div>
</form>
#app.route('/',methods=['GET','POST'])
def index():
if request.method == 'POST':
username = request.form['username']
email_id = request.form['email-id']
print(email_id)
print(username)

Python Flask bad request

I'm making a text based browser game in python and flask but I encountered a strange problem.
When I try to login on my website I get a "bad request" error.
This is my login route:
#app.route('/login/', methods=['GET','POST'])
def login():
if current_user.is_authenticated:
return redirect("/game/", code=302)
# when the form is filled in
if request.method == 'POST':
# register the user
if request.form['regSubmit'] == 'regSubmit':
username = request.form['regUser']
password = request.form['regPassword']
address = request.form['regAddress']
register_user(username=username,password=password,address=address)
print(address)
return redirect("/login/", code=302)
# login user
if request.form['logSubmit'] == 'logSubmit':
print('lol')
username = request.form['logUser']
password = request.form['logPassword']
result = users.find_one({"user": username})
if result and check_password_hash(result['password'], password):
user_obj = User(result['_id'])
login_user(user_obj)
return redirect("/game/", code=302)
return render_template('out.html')
This is my login modal:
<div id="loginModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Login</h4>
</div>
<form method="post">
<div class="modal-body">
<p>Please enter your username and password.</p>
<div class="form-group">
<label class="control-label" for="logUser">Username</label>
<input type="text" name="logUser" class="form-control" id="logUser">
</div>
<div class="form-group">
<label class="control-label" for="logPassword">Password</label>
<input type="password" name="logPassword" class="form-control" id="logPassword">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" name="logSubmit" value="logSubmit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
I believe your code is failing because you're trying to access request.form['regSubmit'], but this field does not exist in your form. Accessing any form fields that do not exist will cause Flask to return a 400 Bad Request error.
To get around this, you can either submit your login and register actions to different Flask views, or you can use a try...except block to catch the KeyError generated by trying to access a non-existent form field.

How to post data via form HTML?

I want to post the data to the server via form. How can I do this?
<div class="panel-body">
<form role="form" action="{% url 'login' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="sender-email" class="control-label">Username:</label>
<div class="input-icon"> <i class="icon-user fa"></i>
<input id="sender-email" type="text" placeholder="Username" class="form-control email">
</div>
</div>
<div class="form-group">
<label for="user-pass" class="control-label">Password:</label>
<div class="input-icon"> <i class="icon-lock fa"></i>
<input type="password" class="form-control" placeholder="Password" id="user-pass">
</div>
</div>
<div class="form-group">
<input class="btn btn-primary btn-block" id="authenticate_user" type="submit" value="Submit">
</div>
</form>
</div>
My views.py
#csrf_exempt
def signin(request):
if request.method == 'POST':
print request.POST.get('sender-email') #prints None
username = request.POST['username'] # throws error, username not available.
password = request.POST['password']
How do I post the data without using jquery? I know of a way of posting through AJAX jquery, but dont wanna do that.
The 'name' attribute of input tags is set as keys of request.GET and request.POST.
Add name attribute to all your input tags.
<input name="username" id="sender-email" type="text" placeholder="Username" class="form-control email">
<input name="password" type="password" class="form-control" placeholder="Password" id="user-pass" >
POST data are populated using the name attribute of your input elements. Change your id attributes or add a name one accordingly. E.g:
<input type="password" class="form-control" placeholder="Password" name="user-pass">
You should also consider using a form to handle your data more easily.

Categories