How to edit (fetch/store) with Summernote textarea + Datastore GAE - python

Until recently I was able to post data to my datastore (Google App Engine). I've now added summernote wysiwyg and now I'm no longer able to add/fetch data from the datastore. Where do you think the problem is?
Main.py
class About(ndb.Model):
text = ndb.StringProperty()
#object
cv = About()
class MainHandler(webapp2.RequestHandler):
def get(self):
title="Exercise"
cv = About.get_or_insert('6684480941064192')
text = cv.text
template_vars={'title': title, 'text':text}
template = JINJA_ENVIRONMENT.get_template('home.html')
self.response.out.write(template.render(template_vars))
def post(self):
cv = About.get_or_insert('6684480941064192')
cv.text=self.request.get("texto")
cv.put()
self.redirect('/')
Html (Material design + bootstrp)
<form class="col s12" form action="/" method="POST" id="frmPost" style="margin-top:25px; margin-bottom:10px;">
<div class="row">
<div class="panel panel-heading" style ="border-radius: 0px; background-color: #e57373;">
<h3 class="panel-title" style ="color: white;">About...</h3>
</div>
<textarea rows="10" id="summernote" form="frmPost" name ="texto" style="margin-top:-10px; display:block;">
{{text}}
</textarea>
</div>
</form>
<script>
$(document).ready(function() {
$('#summernote').summernote({
});
});
</script>

Not sure what summernote is but you probably need to POST your data back to the server somewhere in your HTML/JS. You have the <form> but there doesn't seem to be a way to submit your data back to GAE. You possibly need something like <input type="submit" value="Save Data" /> somewhere inside your <form/>.

Related

Django how to update a template without refreshing/redirecting?

I'm trying to make a simple commenting system where someone can add their comment to a post and it'll show up without having to redirect them or refresh the page. This is what my code basically looks like:
def post_details(request):
details = {}
if request.method == "POST":
request.POST
# Function here for creating a new comment
details['new_comment'] = new_comment
details['post_details'] = post_details
else:
details['post_details'] = post
return render(request, 'post_details.html', details)
The post_details.html shows a post with comments below it along with a form that adds their comment. I tried to add a new block of code in the template file for new_comment and the issue is that when I add a new comment, it will update that part but adding another one won't show up.
I should also note that I have CSV files that store the post and comment details. In my models.py file, I have my classes and methods to read in the CSV files so the function I left out does update the file with the comments. I'm trying to do this without Javascript but I'm open to trying anything, just really want to solidify my understanding of requests. I hope this wasn't confusing.
You can use JavaScript (AJAX) in this situation.
Create a base division in your template for showing your comments.
Then create an input form field for user to write comment.
Give the submit button id such as "addcomment" in my case.
Create the below ajax function with proper input values.
AJAX Function in JAVASCRIPT
$('#addcomment').click(function(){
// Taking_username_from_input_field_with_id_username.
var user = $('#username').val();
var usercomment = $('#usercomment').val(); // Taking_comment_from input_field_with_id_usercomment.
var csr = "{{csrf_token}}"; // Creating CSRF Token
$.ajax({
url: "{% url 'savecomment' blog.blog_id %}",
method:"POST",
data:{
user:user,
usercomment:usercomment,
csrfmiddlewaretoken:csr
},
success:function(data){
form.reset(); // resetting form values.
var output = "";
output =` <div class="comment">
<div class="comment-header d-flex justify-content-between">
<div class="user d-flex align-items-center">
<div class="image"><i class="fa fa-arrow-right"></i></div>
<div class="title"><strong>${data.user}</strong><span class="date">${data.date}</span></div>
</div>
</div>
<div class="comment-body">
<p>${data.comment}</p>
</div>
</div>`
$('.post-comments').append(output); // Appending data_in existing values which loaded_in first run.
//for_updating commentcount
var commentcount = data.number_of_comments;
$('.no-of-comments').replaceWith(`<span class="no-of-comments">(${commentcount})</span>`);
}
});
COMMENTS TEMPLATE
<div class="post-comments">
<header>
<h3 class="h6">Post Comments<span class="no-of-comments">0</span></h3>
</header>
</div>
FORM TEMPLATE
<form id="form" action="#" class="commenting-form">
<div class="row">
<div class="form-group col-md-6">
<input type="text" name="username" value="{{page.username}}" id="username" placeholder="Name"
class="form-control" disabled>
</div>
<div class="form-group col-md-12">
<textarea name="usercomment" id="usercomment" placeholder="Type your comment"
class="form-control"></textarea>
</div>
<div class="form-group col-md-12">
<button id="addcomment" type="button" class="btn btn-secondary">Submit Comment</button>
</div>
</div>
</form>

How handle a Tag field in JS together with Flask Form?

Intro: I can receive the values from input fields in Flask by
var = request.form['description']
and the following HTML:
<form method="post" enctype="multipart/form-data">
<div class="mb-3">
<label for="description">Beschreibung</label>
<textarea name="description" placeholder="Post description"
class="form-control"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
Question: Any idea how to handle a tag field, like e.g. Link , together with Flask Form? How to handle Flask Form and $.Ajax Post request simultaneously? Any hint would be highly appriciated. I did my research but found nothing online.
I found now an easy solution for me. DonĀ“t know if it is very clean but what I did was basically create a hidden field and pass the var from JS to the hidden field inside <form so that i can grab it with request in Flask. I also did this the other way around, passing the variable from Flask to JS. In this way I can use the CSS,JS in the link above outside of <form, i.e. I can press Enter
HTML:
<!-- from JS to Flask -->
<input type="hidden" name="hidden_tags" id="hidden_tags" value="" />
<!-- from Flask to JS -->
<input type="hidden" name="hidden_tags2" id="hidden_tags2" value="{{ post['tags'] }}"/>
in JS:
tags = document.getElementById("hidden_tags2").value.split('/');
document.getElementById("hidden_tags").value = tags
in Flask:
request.form['hidden_tags']

Why is my POST not working after getting values

So I am getting user input from a template that uses css and jQuery, then I'm posting that data back supposedly on click. However, I am not able to access the data as I believe it is not being posted back.
I believe my ajax code is not recognizing the click, can someone please help me out. I spent the whole day trying to figure out what am I doing wrong.
#This is main code
from bottle import run, route, request, template, static_file, post
def main():
#This is main code
#route('/assets/<filepath:path>')
def server_static(filepath):
return static_file(filepath, root='./Gui/assets')
#route('/')
def home():
return template('indexTest')
#post('/home')
def home():
radius=request.forms['radius']
noTr=request.forms['noOdTurbines']
result=radius+noTr
return ({'result': result})
if __name__ == '__main__':
main()
run(host='localhost', port=8080, debug=True)
this is jQuery code
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
<script type="text/javascript">
$(document).ready(function(){
$('form').on('submit',(function(event){
$.ajax({
type: "POST",
url: "/home"
data: {
radius: $('#radius').val(),
noOfTurbines: $('#noOfTurbines').val()
},
error:function(){
alert('Error: something is wrong with values!!')
}
})
event.preventDefault();
});
}));
</script>
</head>
<body>
<form method="POST" action="/home">
<div id="exampleAccount" role="tabpanel">
<div id="exampleAccountForm">
</div>
<div>
<label for="radius">Radius of Swept-Area of Wind turbine:
</label>
<input type="text" id="radius" required>
</div>
<div >
<label for="noOfTurbines">Number of Wind turbines: </label>
<input type="text" id="noOfTurbines" required>
</div>
</div>
</div>
<div >
<button type="submit" class="btn btn-default"
id="submit">Finish</button>
</div>
</form>
</body>
</html>
I have problems with the request.forms type of multidict, so I convert to dict and this solves all my problems. I usually merge the post and string URL objects into one just to make it more flexible.
def merge_dicts(*args):
result = {}
for dictionary in args:
result.update(dictionary)
return result
payload = merge_dicts(dict(request.forms), dict(request.query.decode()))
Just remember, that bottle uses the name not the id of the form element in a post. So make sure all inputs have a name.
(Which I do not see in your example)

how to get the value of checkboxs that checked using Django framework.?

How to get the value of checkboxs that checked and send it to views this is my form !
<form class="form-horizontal form-label-left"method="POST" action="{% url 'paperCustomization_submission'%}">
<div class="col-md-7 col-sm-9 col-xs-12">
{%for question_type in questions_type%}
<div class="checkbox" id="checkbox-question" >
<label>
<input type="checkbox" id="question_type_id" value="{{question_type.question_type}}" onclick="function1();"class="flat" name="checkbox_question"> {{question_type.question_type}}
</label>
</div>
{%endfor%}
</div>
You have missed the name field in the checkbox input. simply add the name field and get the field by name in simple post method in Django as below.
if request.method == 'POST':
isChecked = request.POST.get('checkbox_question')
For checked checkbox you can add Below Jquery code.
$(document).on('change','input.flat', function() {
$('input.flat').not(this).prop('checked', true);
});
You can pass the checkbox input using the name attribute of inside tag
HTML Code will be like
<input type="checkbox" class="form-check-input" name="questions" value={{question_type.question_type}} onchange="pushToArray()"/>
and add this Javascript code inside the head tag
<script>
var questions = []
function pushToArray(event)
{
questions.push(event.value);
return;
}
</script>
where 'questions' is the parameter you want as the input from checkbox and you can parse the request to get these questions as
questions = request.POST.get('questions')

Submit form with input added in the URL and not as parameter

Supposing I have the following Form. Is there a better way to send the value of the input in the URL like in the example "indication_effects/+MY_VALUE" and get rid of the parameter indication=MY_VALUE ?
Maybe it is possible to do it with Django or should I simply use a django form?
Thank you,
<form id="indication-form" class="form-horizontal" method="get">
<div class="form-inline">
<div class="col-md-8">
<input type="text" class="form-control" id="indication-input" name="indication" />
<button class="btn btn-primary" type="submit" id="indication-submit">Submit</button>
</div>
</div>
</form>
var indicationForm = $('#indication-form');
$("#indication-submit").on("click", function () {
indicationForm.attr("action", "indication_effects/" + $("#indication-input").val());
indicationForm.submit();
});
Look, the GET request always will send the form data through url and the POST request always will send the form data through request headers.
It may not look pretty, but it's the way it works.
However, you can do something nice with Vue.js to get what you want.
Disregard your form action, change your submit button from <button> to <a> and build its href dynamically, you can "submit" your form using the form data on your HTML.
Something like this:
<div id="app">
<form id="indication-form" class="form-horizontal" method="post" action=".">
<div class="form-inline">
<div class="col-md-8">
<input type="text" class="form-control" id="indication-input" name="indication" v-model="indication" />
<a :href="getUrl" class="btn btn-primary" id="indication-submit">Submit</a>
</div>
</div>
</form>
</div>
<script src="//unpkg.com/vue"></script>
<script type="text/javascript">
new Vue({
el: '#app',
data: {
indication: '' // Link all your form fields with v-model here
},
computed: {
getUrl: function() {
return '/' + this.indication + '/'; // Build your url
}
}
});
</script>
Vue.js is a powerful and simple Javascript framework, I like it very much.

Categories

Resources