How to insert python variable inside the value of a form? - html

I am trying to make a timer that gets its time from a python variable. But whatever I am doing it's not working.
Here is my python piece of code.
#blogs.route('/individual_set/<int:set_id>')
def individual_set(set_id):
individual_page = Post.query.get_or_404(set_id)
return render_template('forms_page.html', individual_page=individual_page,time_limit = 25)
According to the above code, I am wanting to make the input value to time_limit = 25
Here is the HTML part
<input name = 'set_time' type="hidden" id="set-time" value='1'>
<div id="countdown">
<div id="tiles" class="color-full"></div>
</div>
Inserting {{time_limit}} does not work whereas plain value like value ='5' works

Doing {{ time_limit }} instead of {{time_limit}} worked.

Related

django - change list in POST request

I have a tuple list and wanted to delete or add tuples in it depending on what button has been pressed. Adding tubles is functioning fine but my problem is, that for some reason if Im clicking on the button to delete a tuple, the list resets back the time to the state before the delete happened.
For example I have a list:
ctestformat = [('sung', 4, 15), ('ren', 3, 27), ('lexe', 4, 39)]
after deleting the number 15 I get:
ctestformat = [('ren', 3, 27), ('lexe', 4, 39)]
But after getting another POST request to delete or add, the list resets to the first state as if nothing got deleted
Here is my view to add and delete tuple depending on which button was clicked:
def editorstart(request, ctestformat=[]):
if request.method == 'POST':
"""If clicked on create gap button, create a new gap and put it in ctestformat"""
if 'create_gap' in request.POST:
selectedgap = request.POST['sendgap']
startindex = int(request.POST['startpoint'])-13
ctestformat.append((selectedgap, len(selectedgap), startindex))
ctestformat.sort(key=operator.itemgetter(2))
"""if clicked on deletegap, delete the gap from ctestformat"""
elif 'deletegap' in request.POST:
deleteindex = request.POST['deletegap']
test = [t for t in ctestformat if t[2] != int(deleteindex)]
ctestformat = test
# This function doesnt change anything to ctestformat
modifiedtext = createmodifiedtext(ctestformat)
return render(request, 'editor_gapcreate.html', {"text": modifiedtext, 'ctestformat': ctestformat})
If you have any other questions, just ask :)
EDIT:
added return in my view
my template:
{% extends "base_generic2.html" %}
{% block content %}
<form action="editorgapcreate" id=create method="POST">
<input type="hidden" name="sendgap" id="sendgap">
<input type="hidden" name="startpoint" id="startpoint">
<script src="../static/textselector.js"></script>
<div id="thetext" onmouseup="getSelectionText()">
<h1>{{ text|safe }}</h1>
</div>
{% csrf_token %}
<p></p>
<b>Your current selected gap:</b>
<p id="currentgap"></p>
<input type="hidden" name="text" id="text" value="{{ text }}">
<button type="submit" name="create_gap" id="gapcreate">Create gap</button>
</form>
{% endblock %}
Using a mutable value for a default argument in Python (a list in this case) is not normally a good idea. The list is created once when the function is defined, which means any changes you make to it are visible in subsequent function invocations. However, it seems as though this may be intended in your case.
The reason why you're not seeing the list change, is that the assignment you're making ctestformat = test after filtering out an item has no effect. You need to mutate the original list rather than reassigning, by first finding the index of the item within that list, and then using pop() to remove it. For example:
elif 'deletegap' in request.POST:
deleteindex = request.POST['deletegap']
for i, t in enumerate(ctestformat):
if t[2] == int(deleteindex):
ctestformat.pop(i) # Modify original list
break
...
I would still recommend not using a mutable default argument to achieve this. If you need to share data across requests, you'd be better to use a cache or a database, or possibly session state, depending upon your application requirements.

htmlspecialchars() expects parameter 1 to be string array given

I have an input field in which I am passing an array from my controller as hidden input but its giving me this error of array given.
Code of my view is
<input type="hidden" name="DiseaseDiagnosed[]" value="{{$DiseaseDiagnosed}}">
Code of controller passing the value to view is
return view('/doctorPanel/diagnoseDisease', ['chart' => $chart, 'patient' => $patient, 'symptomsStated' => $symptomsStated, 'DiseaseDiagnosed' => $DiseaseDiagnosed]);
Kindly tell me why I am getting this error
<input type="hidden" name="DiseaseDiagnosed[]" value="{!! jsond_encode($DiseaseDiagnosed) !!}">
Actually, your input is DiseaseDiagnosed is an array which is returned to view.
So you have to use {{ json_decode($DiseaseDiagnosed) }}
You can also try
#foreach($DiseaseDiagnosed as $disease)
<input type="hidden" name="DiseaseDiagnosed[]" value="{{ $disease }}">
#endforeach
Blade Template engine is producing this error. you can't print array like this using {{ }}. When passing this value, you can encode it using 'DiseaseDiagnosed'=>json_encode($DiseaseDiagnosed]), then you can use that syntax. After that when you want to use this value, don't forget to decode it using json_decode()
In order to create an array with inputs you need to have 1 input for each value inside the array. You are appending an array on the value when it only accepts Strings so thats why it warns you that an array was given when a String was expected.
As #Adnan suggested you can solve this using:
#foreach($DiseaseDiagnosed as $disease)
<input type="hidden" name="DiseaseDiagnosed[]" value="{{ $disease }}">
#endforeach
Then in your controller you will recieve the array DiseaseDiagnosed with all the values you inserted, eg: You will recieve all the values within the same array->
dd($request->DiseaseDiagnosed);
// You will see this is an array with all the values

MeteorJS: How to get id to load from collection

I'm trying to load an array (with simple text) and trying to load it up on the template whenever it is called. How do I get the ID from that specific item to get the array that I stored in it?
HTML Template:
<template name="commentMarker">
<div id="viewMarker">
<h3 id="markerTitle">{{markerName}}</h3>
<h6 id="markerCategory">{{markerCategory}}</h6>
<br>
<fieldset>
<legend>Description</legend>
<p>{{markerDescription}}</p>
</fieldset>
<form id="commentForm">
<fieldset>
<legend>Comments</legend>
<input type="text" id="markerId" name="idForComment" value={{markerId}}>
<textarea rows="3" cols="19" name="comment" id="commentArea" placeholder="Insert your comment here..."></textarea>
{{#each comments}}
<p id="oneComment">{{this}}</p>
{{/each}}
</fieldset>
<input type="submit" value="Comment" class="commentButton">
<input type="submit" value="Close" class="exitButton">
</form>
</div>
</template>
JS:
Template.commentMarker.helpers({
comments(){
alert(template.find("#markerId").value);
if(commentArray.length===0) return;
else return commentArray;
}});
This is where I insert the comment into the collection's item and it's working fine
Template.commentMarker.events({
'click .commentButton': function(e, template){
e.preventDefault();
var id = template.find("#markerId").value;
var comment = template.find("#commentArea").value;
Points.update(id, { $push: { comments: comment }});
commentArray = Points.findOne(id).comments;
template.find("#commentArea").value = ' ';
}
I tried with commentArray as a global variable which still is. But I'm at loss how I can get the Id from that specific item, I even put it's Id (with hidden display) in the form to actually be able to insert the comment. But it doesn't help me with showing the comments because I cannot seem to get to this field in the Template.helpers ...
Not entirely sure what you are trying to do. It's almost like as if you are displaying the comments right after you updated in to the collection. It looks like you are doing this entirely on local and not a online collection.
However, storing it as a session would work...or reactive var. Might not be the best solution tho. Basically replace commentArray = Points.findOne(id).comments; with:
Session.set('comments', Points.findOne(id).comments)
Then to get it out in helpers:
let commentArray = Session.get('comments')
It's not safe to use it all the time tho for sensitive data. Also try catch the findOne(id).comments because it does produce errors if it happen to not find it.
NOTE: If you are going to use Meteor.Methods, you cannot use Session. You have to return the id and find it in your helpers.

TextAreaField renders with itself (HTML code in readable text format) as its prepopulated text value

I'm rendering a WTForms TextAreaFields with Jinja2 in a Flask application and it has it's own HTML code as its prepopulated text value, although the default property (which should specify the prepopulated value) is set to empty string ''.
Form definition:
channels = TextAreaField('channels', default='')
Jinja2 template HTML file:
{% for c in e.form.conditions %}
{{ c.form.channels }}
{% endfor %}
Result (rendered, visible to end-user, should be empty string ''):
<textarea id="channels" name="channels"></textarea>
... (other iterations)
Result (HTML):
<textarea class="form-control" id="conditions-0-channels" name="conditions-0-channels"><textarea id="channels" name="channels"></textarea></textarea>
... (other iterations)
I double-checked using the Pycharm debugger and the TextAreaField as a whole object shows as the HTML result above, even though none of its properties contain the visible result string (also above), and the default property is equal to '' even though the result doesn't show so.
Bonus hint: for some reason, if the form containing the channels field is not part of a FormField inside a WTForms FieldList, this problem does not occur.
I don't know what on earth is going wrong with this combination of FieldList, FormField and TextAreaField, but if you call {{ c.form.channels.data }} (with extra .data) in your Jinja2 template HTML file instead of {{ c.form.channels }} then everything works fine.
Wow THANK YOU! I'm not sure what's going on either but this solved the issue for me too. I had some similar findings shown below:
Forms.py
class ChannelForm(FlaskForm):
notes = TextAreaField('Notes', render_kw={'class': 'form-control'}, default="")
channels.html
# These:
{{ channels.notes.data }} # Working solution
{{ channels.notes(value="test Value") }}
# Render these:
<textarea class="form-control" id="notes" name="notes"></textarea>
<textarea class="form-control" id="channels-0-notes" name="channels-0-notes" value="Test Value"><textarea class="form-control" id="notes" name="notes">
Test</textarea>

How to bind data from datepicker to a regular ng-model

jsp page:
<label>Script ID:</label>
<input name="scriptId" type="text"
ng-model="selectedScript.scriptId"
ng-disabled="true"
value="{{selectedScript.scriptId}}"
/>
<form>
<h1>Date Pannel</h1>
<fieldset>
Pick a start date:<br>
<input ng-disabled = "mode =='BROWSE'" type="date" id="datePickerStart" ng-model="parent.startDate" onchange="document.getElementById('datePickerEnd').setAttribute('min', document.getElementById('datePickerStart').value)"><br><br>
Pick an end date:<br>
<input ng-disabled = "mode =='BROWSE'" type="date" id="datePickerEnd" ng-model="parent.endDate" ><br><br>
<button ng-disabled = "mode =='BROWSE'" ng-click="setDates()"
>Set Dates</button>
</fieldset>
</form>
controller.js
$scope.parent = {startDate:''};
$scope.parent = {endDate:''};
$scope.selectedScript.startDate = null;
$scope.selectedScript.endDate = null;
$scope.setDates = function setDates() {
$scope.selectedScript.startDate = $scope.parent.startDate.getTime();
$scope.selectedScript.endDate = $scope.parent.endDate.getTime();
myAppFactory.setDates($scope.selectedScript.startDate, $scope.selectedScript.endDate, $scope.selectedScript.src).success(function(data) {
$scope.selectedScript.src=data;
});
}
That's all the code i need to get some stuff done...
Now I have a table on my jsp page...
<tr
ng-repeat="s in scripts
ng-click="selectScript(s, $index)"
ng-class="getSelectedClass(s)">
<td>{{s.scriptId }}</td>
<td>{{s.fileName }}</td>
</tr>
controller.js
$scope.selectScript = function(script, index) {
if ($scope.mode != 'BROWSE')
return;
$scope.parent.startDate = $scope.selectedScript.startDate; <-- this part
$scope.parent.endDate.setTime = $scope.selectedScript.endDate; <--and this
$scope.selectedScript = script;
$scope.selectedRow = index;
};
When I save the script, the data in the database has startDate and endDate
that works...
My problem is that selectedScript as a model, in the code above, don't has any value in startDate and endDate...it's null (but the fields exist, and the database has the data I need)
But I need somehow to make it possible that parent.startDate and endDate are bound to the selectedScript's startDate and endDate...
Btw, i 1st tried to make the ng-model of the datepicker like selectedScript.startDate, but that didn't work...
Later I found out that the datepicker has it's own scope, and that's causing my problems...at least I believe so.
I just hope that I have made myself clear...
Can you help me?
I think your issue is because when you retrieve the data from the database, it passes it as a string, which isn't a format that the datepicker can read.
Essentially what you need to do is parse it as a Date attribute, to do this you can do;
$scope.parent.startDate = new Date($scope.selectedScript.startDate);
$scope.parent.endDate = new Date($scope.selectedScript.endDate);
Use this in the relevant places to parse as a date, or you can set up a watch to do it for you whenever the value is changed;
$scope.$watch('parent.startDate', function(startDate){
$scope.parent.startDate = new Date($scope.parent.startDate);
});
You can only use $watch for single values, or you can watch the whole object as 'parent'.
Hope it helps!