I'm getting a bad value when I return this option. For example, when i send n = "Arnold, Robert | ID: 1" as an option, it shows up on the web page, but when the user clicks submit, only "Arnold," is sent to my Flask Server. I'm trying to get the ID value out.
Does anyone know how to retrieve the entire option value from the form or another way to get the ID out of the string?
Here's the HTML
<h2>Donors</h2>
<form method="POST" action="/display_donor">
<select name="selected_donor">
{% for n in donors %}
<option value={{n}}>{{n}}</option>
{% endfor %}
</select>
<br />
<br><input type="submit" value="View donor"/>
</form>
Here's the relevant Flask function
#app.route('/display_donor', methods=['POST'])
def display_donor():
temp_id = request.form['selected_donor']
print "temp_id"
print temp_id
final_id = re.sub('[^0-9]','', temp_id)
print "final_id"
print final_id
display_value = 1
cursor = g.conn.execute("SELECT name,donor_id FROM donors")
donors = []
for result in cursor:
temp_string = result['name'] + " | ID: " +result['donor_id']
donors.append(temp_string)
# can also be accessed using result[0]
cursor.close()
print "this"
print final_id
#Returns a specific instance of transaction as specified by user
cursor = g.conn.execute("SELECT * FROM donors D WHERE D.donor_id='%s'" % final_id)
values = []
for result in cursor:
values.append(result['donor_id'])
values.append(result['name'])
values.append(result['donor_type'])
cursor.close()
#denote attribute names
attribute = []
attribute.append('donor_id')
attribute.append('name')
attribute.append('donor_type')
return render_template("donors.html",attribute=attribute,values=values,donors=donors,display_value=display_value)
I fixed this issue by sending the values separately rather than as a single string. This got me out of all the parsing and allowed me to print out the values like so:
<h2>Donors</h2>
<form method="POST" action="/display_donor">
<select name="selected_donor">
{% for n in donor_ids %}
<option value={{n}}>{{ donor_names[loop.index0] }} | ID: {{n}}</option>
{% endfor %}
</select>
<br />
<br><input type="submit" value="View donor"/>
</form>
Related
I have below form which selects the data and redirects to the page user_data
It selects the date and redirects to another page.
Am able to get the data using request.form['Period'] method in python.
But this is not getting called in form action <form action = "/user_data/{{period}}" method="POST"> period variable is empty resulting in Not Found error.
Is there a way to select a value and pass it into a same form
<form action = "/user_data/{{period}}" method="POST">
<label for = "Period" id = "Period">Period</label>
<input list="User_Listing_Period" id ="User_Lst_Period" name = "Period">
<datalist id = "User_data_Period">
{% for row in user_dat_filter %}
<option name = "User_Dat_Period" value = "{{row[0]}}"></option>
{% endfor %}
</datalist>
<div class="submit">
<label for = "Submit" id = "Submit"></label>
<button type="submit">Submit</button>
</div>
two options here:
let form direct to url /user_data, and based on the Period value renders the page i.e it renders the data for that month.
as value is based on user selection, JS can be utilized.
<html>
<body>
<form action = "/user_data/{{period}}" method="POST" id="myForm">
<label for = "Period" id = "Period">Period</label>
<input list="User_Listing_Period" id ="User_Lst_Period" name = "Period">
<datalist id = "User_Listing_Period">
<!-- I commented this, so can check in HTML, you can go with your code
{% for row in user_dat_filter %} -->
<option name = "User_Dat_Period" value = "Aug22"></option>
<option name = "User_Dat_Period" value = "Sep22"></option>
<option name = "User_Dat_Period" value = "Oct222"></option>
<!-- {% endfor %} -->
</datalist>
<div class="submit">
<label for = "Submit" id = "Submit"></label>
<button type="submit">Submit</button>
</div>
</form>
<script>
const myform= document.getElementById("myForm")//identify the form
// add a listener to myform
myform.addEventListener('submit', async (e) => {
e.preventDefault(); //block default submit
const selectedOption=document.getElementById("User_Lst_Period")
let value = selectedOption.value
document.location.href='/user_data/' + value //redirect to value selected by user
})
</script>
</body>
</html>
I am trying to make a html dropdown and pass the values into Postgrase SQL database. My dropdown values are being retrieved from another database table. It gives me a MultiValueKeyDictError every time I submit the form. I know I can use forms.py to do the same thing but I want to explore the HTML way of doing this.
My HTML file
<form action = "" method = "post">
{% csrf_token %}
<label for = "LogType"></label>
<input id ="LogType" type = "text" value = "{{ user.department }}">
<label for ="DelayCategory">Delay Category</label>
<select id = "delaycategory" class = "form-control">
{%if user.department == 'TechAssembly'%}
{%for techdelay in techdelay%}
<option value = "{{ techdelay.DelayCode }}">{{ techdelay.DelayCategory}}</option>
{%endfor%}
{%endif%}
{%if user.department == 'Testing'%}
{%for testdelay in testdelay%}
<option value = "{{ testdelay.DelayCode }}">{{ testdelay.DelayCategory}}</option>
{%endfor%}
{%endif%}
</select>
<label for = "iterations">Iterations</label>
<input type = "number" id = "iterations">
<center><input type="submit" value=Submit id = "button"></center>
</form>
My Views.py file
def rulesView(request, user_name):
testdelay = TestingDelayCategory.objects.all()
techdelay = TechDelayCategory.objects.all()
if request.method == "POST":
rulesnew = rules()
rulesnew.DelayCategory = request.GET['DelayCategory']
rulesnew.LogType = request.POST('LogType')
rulesnew.iterations = request.POST('iterations')
rulesnew.save()
context = {
'techdelay':techdelay,
'testdelay':testdelay,
}
return render(request, 'rules/rules.html', context)
rulesnew.DelayCategory = request.GET['DelayCategory']
rulesnew.LogType = request.POST('LogType')
rulesnew.iterations = request.POST('iterations')
Have a second look at this: request.GET should be request.POST and request.POST('LogType') should be request.POST['LogType'] same with iterations.
The error message should include the exact line where the errors was raised. So it would have been way easier to debug if you have told us that the error was raised e.g. in this line rulesnew.LogType = request.POST('LogType')
Hi i have question possible make option drop list with value group id and option text with groupname
My code is simple, first i make query for pick group id and name from database and then render template in my html place where is multiselect option.
html code
<select class="selectpicker" name="ms1" id="ms1" multiple>
{% for x in grouplist %}
<option value="{{ x }}">{{ x }}</option>
{% endfor %}
</select>
python code
def calendar():
a = []
query = "SELECT groupId, groupName from dbo.CalGroups"
cursor.execute(query)
for row in cursor:
a.append(row[0])
app.logger.debug(a)
return render_template('calendar.html', grouplist=a)
for now in option i can see only id
any idea how to split for value and for text in option? All help will be appreciated
I think you only getting groupId in your list "a" like row has two values one zero index, you have groupId and on the first index, you have groupName like this [groupId, groupName] you only saving row[0] which is groupId.That's why you have groupId in your list a. I suggest you, use a dictionary if you want to store both groupId and GroupName.
def calendar():
a = {}
groupId = []
gourpName = []
query = "SELECT groupId, groupName from dbo.CalGroups"
cursor.execute(query)
for row in cursor:
groupId.append(row[0])
groupName.append(row[1])
a["groupId"] = groupId
a["groupName"] = groupName
app.logger.debug(a)
return render_template('calendar.html', grouplist=a)
Then html code should be like this.
<select class="selectpicker" name="ms1" id="ms1" multiple>
{% for x in range(len(grouplist["groupId"])) %}
<option value="{{ grouplist["groupId"][x] }}">{{ grouplist["groupName"][x] }}</option>
{% endfor %}
</select>
I am facing issue while appending fieldlist through append_entry in flask-wtf.
I am able to add one row of fields from fieldlist but after adding first row, i am not able to add second row.
No errors are shown.
In first attempt a new row is added of field list items and in server log "Data is King" and "True" is printed (I have included this to see if add button sends data and loop actually goes through).
In second attemt new row is not added but page reloads and in server log "Data is King" and "True" is printed (This means loop is executed but append_entry command does not work).
I found same question asked 4 years ago, but solution given in that question's accepted answer does not solve the problem.
Below is the link.
https://stackoverflow.com/questions/8637831/cant-append-entry-fieldlist-in-flask-wtf-more-than-one#=
I have tried all the combinations but nothing solves the problem (am upto this problem for more than 48hrs now).
Can someone help please.
form.py Data
class FormCont(FlaskForm):
description = StringField('Description',validators=[DataRequired()])
start_time = FloatField('Start Time',validators=[DataRequired()])
class AddItemCont(FlaskForm):
a = FloatField(validators=[DataRequired()])
b = FloatField(validators=[DataRequired()])
c = FloatField(validators=[DataRequired()])
item_cont = FieldList(FormField(FormCont), min_entries=0, max_entries=100)
add_item_cont = SubmitField("Add")
remove_item_cont = SubmitField("Remove")
submit = SubmitField()
view.py data
#additem.route('/additem/', methods = ['GET','POST'])
def additemcont():
form = AddItemCont(request.form)
if form.add_item_cont.data:
form.item_cont.append_entry()
print ("Data is King")
print (form.add_item_cont.data)
return render_template('entry.html',form=form)
entry.html data
<form action="{{url_for('additemcont')}}" method='POST' name='AddItemCont' class="form-horizontal">
{{ form.hidden_tag() }}
<div class = "row">
<div class="col-md-1" >
<form action="" method="POST" class="form-horizontal"><button type="submit" class="btn btn-success btn-xs" name="add_item_cont" value="add_item_cont"><span class="glyphicon glyphicon-plus" aria-hidden="true"></button>
</form>
</div>
</div>
<div class = "row"><div class="col-md-12" >
{% for x in form.item_cont %}
{% for i in x %}
{{ i (class="form-control") }}
{% endfor %}
{% endfor %}
</div></div>
Have you tried initializing the form and passing it to append_entry?
#additem.route('/additem/', methods = ['GET','POST'])
def additemcont():
form = AddItemCont(request.form)
if form.add_item_cont.data:
### here
form_cont = FormCont()
form.item_cont.append_entry(form_cont)
####
print ("Data is King")
print (form.add_item_cont.data)
return render_template('entry.html',form=form)
I'm a learner in Python and Django.
I am trying to pass selected checkboxes to my views and then make a get() call to fetch related objects, but keep getting the error DoesNotExist, even though the object is present in the database.
I tried changing the get() parameters but it still shows the same error, as if it just cannot fetch the database. Please help!
ERROR IS IN THE #ed LINE
Here is my views.py
def manage(request):
if request.POST.get('taskname'):
name = request.POST.get('taskname')
end = request.POST.get('enddate')
emp = User.objects.get(username = request.user.username)
print emp.username
try:
newtask = Task(taskname = name, deadline = end, status = 'incomplete', empid = emp)
newtask.save()
except:
print "not saved"
my_tasks = Task.objects.filter(empid = emp)
return render(request, 'ellipse/dashboard.html', {'employee': emp, 'tasks': my_tasks})
else:
selected = request.POST.get('dropdown')
if selected == 'Delete':
tasks = request.POST.getlist('t')
emp = User.objects.get(username = request.user.username)
for seltask in tasks:
#deltask = Task.objects.get(taskname=seltask)
deltask.delete()
my_tasks = Task.objects.filter(empid = emp)
return render(request, 'ellipse/dashboard.html', {'employee': emp, 'tasks': my_tasks})
And, my html:
<div>
<form action="/ellipse/manage/" method="post">
{% csrf_token %}
<p>Taskname <input type="text" name="taskname"></p>
<p>Deadline <input type="date" name="enddate"></p>
<select name="dropdown">
<option selected="selected" disabled>Select action :</option>
<option value="Add">Add</option>
<option value="Delete">Delete</option>
<option value="Mark as complete">Mark as complete</option>
<option value="Mark as incomplete">Mark as incomplete</option>
</select>
{% if tasks %}
{% for tasko in tasks %}
<p><tr><td><input type="checkbox" name="t" value={{ tasko.taskname }}/></td><td>{{ tasko.taskname }}</td><td>{{ tasko.deadline }}</td><td>{{ tasko.status }}</td></tr></p>
{% endfor %}
{% endif %}
<p><button type="submit" name="modify">Modify</button></p>
</form>
</div>
I am clueless on how to proceed further and it'd be great help if this issue can be resolved. Thanks in advance!
Well your get looks jacked up.
emp = User.objects.get(username = request.user.username)
should probably be something like this.
emp = User.objects.get(id=request.user.id)
You could probably do this to...
emp = User.objects.get(user=request.user)