How to change Flask WTForm field value in HTML using javascript? - javascript

I have this simple hidden field in an HTML form:
<input type="hidden" id="response" name="response">{{ form.response}}</div>
and I want to change the it's value so that I can use it using flask and WTForms later on.
I tried this:
function(token){
document.getElementById('response').value = token
}
and the function is being called with a valid token, but no success.
Any suggestions?

The input field for a form is created as follows, where additional arguments like a label or validators are possible.
class ExampleForm(FlaskForm):
response = HiddenField()
submit = SubmitField()
The following code is required to request the value on the server side.
#app.route('/', methods=['GET', 'POST'])
def index():
form = ExampleForm(request.form)
if form.validate_on_submit():
print(form.response.data)
return render_template('index.html', **locals())
If you now render within the template, the attributes name and id are set automatically. The value corresponds to the identifier of the variable to which the input field was assigned. To query and set the value, you can either use a selector with the name attribute or the id of the input field.
<form method="post">
{{ form.csrf_token }}
{{ form.response }}
{{ form.submit }}
</form>
<script type="text/javascript">
(() => {
const token = 'your token here';
let responseField;
// Selecting the input field based on the id attribute,
responseField = document.getElementById('response');
responseField.value = token;
// or select based on the name attribute.
responseField = document.querySelector('input[name="response"]');
responseField.value = token;
})();
</script>

Related

Why am I getting a JSON error and how do I fix it

I am trying got take the value that is inserted into the first and last name fields and then take that and insert it into a MySQL database backend that I have running using restAPI. I got some help to fix the form but I am trying to find the error when I try to take the input form the form and enter it in the database
The table code is this
<div class="superhero">
<h1>Lets add our first name </h1>
<form action="/add_user" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<form action="/add_user" method="post">
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
Then this is taken into the nodeJS server with this command
app.post('/add_people', function(req, res){
axios.get('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
Then at the end it is going to be taken to the RestAPI with that is using this route
#app.route('/api/adduser', methods = ['POST']) # This is a post method because the user needs to be able to add info
def adding_stuff():
request_data = request.get_json() # Gets the info from the table and converts to JSON format
new_fname = request_data['firstname']
new_lname = request_data['lastname']
conn = create_connection("", "", "", "")
sql = "INSERT INTO restaurantusers (firstname, lastname) VALUES ('%s', '%s');" % (new_fname, new_lname) # This sql statement will then be uploaded to the databse to add a new record
execute_query(conn, sql) # This will execute the query
return 'Post worked'
Sorry if what I am asking sounds really complicated. Professor goes too fast in class and I've been trying to find out how to do this for sometime with no luck.
UDATE: I later changed the two items as suggested. The route is
app.post('/add_people', function(req, res){
axios.post('http://127.0.0.1:5000/api/adduser')
.then((response)=>{
var restlist = response.data.results;
console.log(restlist);
// Now we will execute the results in the page named thanks
});
});
and the form is now
<form action="/add_people" method="post">
<input type = "text" firstname = "firstname">
<h1>Lets add our last name </h1>
<input type = "text" lastname = "lastname">
<input type="submit" class="btn btn-primary">
</form>
I get the error that
},
isAxiosError: true,
toJSON: [Function: toJSON]
}
and also this error on the restAPI window
TypeError: 'NoneType' object is not subscriptable
First, you'll need to update your form and inputs to accept user input properly by using the value attribute on the <input> so instead of
<input type = "text" firstname = "firstname">
<input type = "text" lastname = "lastname">
Do this
<input type="text" value="firstname">
<input type="text" value="lastname">
this will send the values firstname and lastname to your API.
If you need to dynamically accept user input you'll need to watch input changes using javascript and handle the form submit with it too. Check
input value attribute and Javascript form.
To send the data from your node server to your python server you'll need to update
axios.post('http://127.0.0.1:5000/api/adduser')
To
axios.post('http://127.0.0.1:5000/api/adduser', { first_name: req.body.firstname, last_name: req.body.last_name })
Because that way you're passing the form data inside req.body to your python server

stop dynamic add field to form when form is invalid

Followed below code to add and display etra fields to forms dynamically with "Add another" button. Code is working but problem is on "Add another" button click (when form in invalid) additional form fields are added to form but not displayed. Want to make sure when form is invalid extra fields are not added to form.
Forms
class MyForm(forms.Form):
original_field = forms.CharField()
extra_field_count = forms.CharField(widget=forms.HiddenInput())
def __init__(self, *args, **kwargs):
extra_fields = kwargs.pop('extra', 0)
super(MyForm, self).__init__(*args, **kwargs)
self.fields['extra_field_count'].initial = extra_fields
for index in range(int(extra_fields)):
# generate extra fields in the number specified via extra_fields
self.fields['extra_field_{index}'.format(index=index)] = \
forms.CharField()
View
def myview(request):
if request.method == 'POST':
form = MyForm(request.POST, extra=request.POST.get('extra_field_count'))
if form.is_valid():
print "valid!"
else:
form = MyForm()
return render(request, "template", { 'form': form })
HTML
<form>
<div id="forms">
{{ form.as_p }}
</div>
<button id="add-another">add another</button>
<input type="submit" />
</form>
JS
<script>
let form_count = Number($("[name=extra_field_count]").val());
// get extra form count so we know what index to use for the next item.
$("#add-another").click(function() {
form_count ++;
let element = $('<input type="text"/>');
element.attr('name', 'extra_field_' + form_count);
$("#forms").append(element);
// build element and append it to our forms container
$("[name=extra_field_count]").val(form_count);
// increment form count so our view knows to populate
// that many fields for validation
})
</script>

Django set form value equal to another form value in template

I want to get the following goal: I have two forms in one view, form1 and form2. The model are the following:
Class Model1(models.Model):
var_1=models.CharField()
var_2=models.CharField
Class Model2(models.Model):
var_1=models.CharField()
var_3=models.CharField
I have just set both form in the same view with a single submit button. Now I want to have the possibility to set var_1 from the form1 also for the var_1 of the Model2 (becouse are equal) when the client fill the form1. It's possible to get it?
This one my views.py
def example(request):
if request.method == 'POST':
form1 = Model1Form(request.POST)
form2 = Model2Form(request.POST)
if form1.is_valid() and form2.isvalid():
print("Il form รจ valido")
new_input1 = form1.save()
new_input2=form2.save()
else :
form1 = Model1Form()
form2 = Model2Form()
context= {
'form1': form1,
'form2':form2,
}
return render(request, "", context)
Suggest that you set the value of the field from the other form before saving.
if form1.is_valid() and form2.isvalid():
form2.cleaned_data['var_1'] = form1.cleaned_data['var_1']
form1.save()
form2.save()
I assume that you are not showing the var_1 field on both forms? If you were showing both this would overwrite the value of var_1 for form2.

Variable within a object reference

I'm getting the username from the input field and sending it as the parameter to the searchUser function. What it returns the username with a value of more objects.
so if I send 'daveeeeeed' in the input field and submit then it sends back
{"daveeeeeed":{"id":30155374,"name":"daveeeeeed","profileIconId":577,"summonerLevel":30,"revisionDate":1443840218000}}
so in my html document I'm trying to access res.'daveeeeeed'.name to print out the name from the request. But obviously {{ res.username.name }} isn't working. and in the javascript I cant use $scope.res = data.username.name.
My question is; how do I use a variable from a object? ex.
my goal
res.username.name //replace username with whatever was send in form
<form>
<input type="text" ng-model="username" placeholder="username" name="username" />
<button ng-click="searchUser(username)" class="btn btn-primary">Submit</button>
</form>
{{ res }}
here's the javascipt
$scope.searchUser = function(username){
$http.get('https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + username + '?api_key=<key>').
success(function(data) {
$scope.res = data;
}).error(function(err) {
$scope.res = "User not found";
});
}
Adding Answer from comment:
You can add username to $scope before making http call. Then you can access it in your DOM template like this {{ res[username] }}.
So Your code should look like this:
$scope.searchUser = function(username){
$scope.username = username; // Notice this change
$http.get('https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' + username + '?api_key=<key>').
success(function(data) {
$scope.res = data;
}).error(function(err) {
$scope.res = "User not found";
}
);
}
Template should look like this:
{{ res[username] }}
you can do it in two ways -
Method 1 :
When returning the result, make the property of the object a static value (e.g. instead of sending daveeeeeed, send user).
{"user":{"id":30155374,"name":"daveeeeeed","profileIconId":577,"summonerLevel":30,"revisionDate":1443840218000}}
this way, you can display the name as :
<div> {{res.user.name}} </div>
Method 2
If you follow your own way,
<div> {{res[username].name}} </div>

User input not saved in model with Javascript

Building a site so users can add topics onto a site and ask then Q&A. Using AJAX, the "Add Media" button on the home page loads my Add Media Form (text and an image) to the site. The box is rendering fine with the correct forms, but after hitting Submit the form doesn't save in the database. When just rendering the form onto a new HTML page without jquery, the model works just fine and the input is saved. How do I get the information submitted in a jquery lightbox to be saved in the database too?
So this is the html page
#home.html
Add Media
<div id="login-box" class="addmovie-popup">
This is the jquery that goes with it
#home.js
$(document).ready(function() {
$('.block3 a').click(function(ev) {
ev.preventDefault();
var url = $(this).attr('href');
$('#login-box').load('http://127.0.0.1:8000/home/add_movie/');
});
});
The URL conf
#urls.py
url(r'^add_media/$', 'add_media'),
The view for adding media
#views.py
def add_media(request):
if request.method == "POST":
form = MediaForm(request.POST, request.FILES)
if form.is_valid():
form.save(user = request.user)
return HttpResponseRedirect("/home//")
else:
form = MediaForm()
return render_to_response("qanda/add_media.html", {'form': form}, context_instance = RequestContext(request))
And the HTML form that it is rendering
#add_media.html
<h1> Add Media:</h1>
<form enctype = "multipart/form-data" action = "" method = "post">{% csrf_token %}
{{ form.as_p }}
<input type = "submit" value = "Add" />
<input type = "hidden" name = "next" value = "{{ next|escape }}" />
</form>
If you're loading HTML into your page dynamically action = "" would point to the current page, which clearly doesn't handle your POST requests.
Set the action to the correct URL.

Categories

Resources