I have the following code in the main.py file. It appears to work in all instances, note when I print out user_details, it prints out the tuple: test,test,test (filled in to the form), so the post request is working. However, somehow, it is not being actually written to the database.
Main nature of error: The insertion is not taking place.
Can someone spot an error in my code?
#ADD COMMENT GET POST REQUEST FUNCTION
#app.route('/add',methods=['GET','POST'])
def addcomment():
if request.method=="GET":
return render_template('addcomment.html')
else:
user_details=(
request.form['title'],
request.form['name'],
request.form['comment']
)
#print(user_details)
insertcomment(user_details)
return render_template('addsuccess.html')
#INSERTING comments into the actual database
def insertcomment(user_details):
connie = sqlite3.connect(db_locale)
c=connie.cursor()
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
c.execute(sql_insert_string,user_details)
connie.commit
connie.close()
print(user_details)
def query_comments():
connie = sqlite3.connect(db_locale)
c=connie.cursor()
c.execute("""
SELECT * FROM comments
""")
userdata=c.fetchall()
return userdata
My suspicion is that there is something wrong with these lines (that is the second function)
insertcomment()
connie = sqlite3.connect(db_locale)
c=connie.cursor()
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
c.execute(sql_insert_string,user_details)
The def addcomment(): function works fine as far as I can see, rendering and returning the right html page on clicking submit.
On the html side, the only thing I can think of that MAY be causing an error is the order of the fields. In the database the fields are Name, Title, Comment (in that order), but in the HTML and the query, they are Title, Name, Comment (in that order specified).
For reference, the HTML file (the form that accepts that data) is below:
<div class="form-group">
<label for="exampleInputEmail1">Title (or catchy caption!)</label>
<input type="text" class="form-control" id="title" name="title" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Add your amazing answer here:</label>
<textarea class="form-control" id="comment" name="comment" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
On the home page, the data is rendered as follows. I've had to switch the numbers around as you can see, as 2= title 1=name and 3 = comment
{% for user in user_data%}
<tr>
<th scope="row">{{user[0]}}</th>
<td>{{user[2]}}</td>
<td>{{user[1]}}</td>
<td>{{user[3]}}</td>
</tr>
{% endfor %}
Whether the above has anything to do with the error, I don't know (the order)...but I cannot think why.
Finally, here is the table populate .py file. You'll notice there is one extra field - date. Again, could this be a factor?
#populate database file
import sqlite3
db_locale='users.db'
connie=sqlite3.connect(db_locale)
c=connie.cursor() #use this to create commands
#creating a multi-line instruction
c.execute("""
INSERT INTO comments (name,title,comment,date_posted) VALUES
('Ruth Marvin','42','Yeah.Someone was going to say 42','20th July 2050'),
('Jonathan Peter','Meaning?','Surely we need to first define meaning','13th August 2050')
""")
connie.commit()
connie.close()
Can anyone explain why the data is not being POSTED/INSERTED into the database.
The error is in the function insertcomment(). You are missing the brackets with commit:
connie.commit
Just change to:
connie.commit()
which will save the changes to the database. Everything else looks fine including the database query. You are right in using a parameterised query.
sql_insert_string="INSERT INTO comments (title, name, comment) VALUES (%s,%s,%s)"
c.execute(sql_insert_string, user_details)
connie.commit()
this should work. Wrap your db operations into a try, except block to figure out whats wrong with your queries.
try:
sql_insert_string="INSERT INTO comments (title, name, comment) VALUES (%s,%s,%s)"
c.execute(sql_insert_string, user_details)
connie.commit()
except Exception as e:
print(e)
You need to format your SQL insertion string using Python's format() function from the standard library.
Your code:
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
Should be like this:
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES ({}, {}, {})'.format(user_details[0], user_details[1], user_details[2])
Then on your c.execute line just pass sql_insert_string as a parameter. Also, I've found that the flask-sqlalchemy module saves countless headaches, but kudos to you for taking the time to learn SQL and coding it like this.
Related
I need to access the input field in the below html. The way the page is setup I need to chain using the 'Address Line 1' text and then sending text to the input field. The input field id changes and so doesn't the layout of the fields depending on user preference. I am struggling. If you need some more information feel free to ask I did not want to overload with too much information.
<td class="labelCol requiredInput">
<label for="00N36000000xina"><span class="assistiveText">*</span>Address Line 1</label>
</td>
<td class="dataCol col02">
<div class="requiredInput">
<div class="requiredBlock"></div>
<input id="00N36000000xina" maxlength="255" name="00N36000000xina" size="20" tabindex="4" type="text">
</div>
</td>
I have accessed like this:
element(by.css('div.pbSubsection:nth-child(3) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > input'))
However depending on where the user puts the fields it can move around. So what I was hoping was to be able to access the label\ and use that to pinpoint its input field.
I don't know protractor but I cobbled together some code that hopefully will work or be close and I'll give you the thought process and some info and hopefully you can use it to fix my code, if needed, and solve the problem.
Start by finding an element by XPath, "//label[text()='Address Line 1']". This searches for a LABEL tag that contains "Address Line 1". Once you find that element, get the label attribute. From your HTML, this label is the id for the INPUT element you want. Now use the id to find the element and do with it what you want.
id = element(by.xpath("//label[text()='Address Line 1']")).getAttribute("label")
input = element(by.id(id))
input.sendkeys("some text")
Haven't tested this myself, but you could try something like this:
// $ is shorthand for element(by.css())
$('div.assistiveText').getAttribute('for').then(function (val) {
// locate the <input> by the value of the attribute on <label>
element(by.id(val)).sendKeys('abc'); // replace sendKeys with your intended function
});
Or if that first locator on the label isn't specific enough, swap out $('div.assistiveText') for element(by.cssContainingText('Address Line 1'))
I tried it for other attributes (I don't have a for attribute anywhere in my app) and it seemed to work for me.
Try this:
List<WebElement> elementList = driver.findElements(By.cssSelector("tbody > tr"));
for (WebElement element : elementList) {
if(element.findElement(By.cssSelector("td.labelCol > label")).getText().equalsIgnoreCase("Address Line 1")) {
element.findElement(By.cssSelector("input[type='text']")).sendKeys("textToInput");
}
}
I'm making a simple booking system with the help of Laravel. The times that is booked is for an imaginary car company that rent cars. So you rent a car by booking the time. I'm pretty far into the project and I'm almost finished. I just have a small problem. I dont know how I can make my booked times "not bookable" so to say.
What I want to be unique is the date of the booking. In my migration for the "booked" times (the table is called "times") I have already set the column "date" to be unique:
public function up()
{
Schema::create('times', function (Blueprint $table) {
$table->integer('car_id')->unsigned();
$table->date('date');
$table->timestamps();
$table->primary(array('car_id', 'date'));
});
}
The date "integer" makes it so that it is unique and I can not book it twice. But what I want to do is check if the booked time is in the Carbon time frame of the ten days from present day. Those times is made like this:
$dt = Carbon::now('Europe/Stockholm');
for ($i = 0; $i < 10; $i++) {
$dates[$i] = $dt->addDays(1)->toDateString();
}
Then I send the $dates variable to my view and display them like this:
<ul class="list-group">
#foreach ($dates as $date)
<form method="POST" action="/{{ $car->id }}/time">
{{ csrf_field() }}
<li class="list-group-item">
<input type="hidden" name="date" value="{{ $date }}">
{{ $date }}
<input type="submit" value="Boka" class="btn btn-primary"/>
</li>
</form>
#endforeach
</ul>
So then if I press the "Boka" button the time is put in the "times" table, and because I use relationship I reach it with $car->time, like that I can get all the booked times on that specific car.
I show all the times that are booked like this in my view:
<ul class="list-group">
#foreach ($car->time as $time)
<li class="list-group-item">
{{ $time->date }}
<form method="POST" action="/delete/time/{{ $time->car_id }}/{{ $time->date }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<input type="submit" value="Delete" class="btn btn-danger"/>
</form>
</li>
#endforeach
</ul>
So basically what I want to do now is to check if the date from Carbon is in the "times" table I want to remove the "Boka" button from the view..
My teacher tells me to use this code in some way:
$this->validate($request, [
'date' => 'exists:times,date'
]);
I know what this snippet of code does, it checks the request sent if the date from the form exist in the times table on the column date. But I just don't know where to use it. Ive tried in my "TimesController" where I add the dates to the "times" table like this:
public function update(Request $request, Car $car, Time $time) {
$this->validate($request, [
'date' => 'exists:times,date'
]);
$times = new Time;
$times->date = $request->date;
$car->time()->save($times);
return back();
}
But this doesn't work the way I want it to. It checks if the date is in the table, and if it is. It ads it. But the problem is, the date must be unique so I get an error message that says the date isn't unique. That's good but not what I want. So if I add a date that isn't booked yet. It doesn't add the date like it should. I check what error I get by writing this code in my view:
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
And the error it output said: "The selected date is invalid."
So what I get from that is that my validation code checks if the request is in the database then if it is, the date is added. But if the date isn't already in the "times" table it doesn't get added. That is the exact opposite of what I want..
I tried putting it in my CarsController to where I make up the dates with the help of Carbon as I showed earlier. But I just can't get anything out of that..
I know this post is kinda long. But I wanted to get as much information in as possible. I would really appreciate some help.
TL/DR: What I want to do is use the Validate function in Laravel to check if my dates for booking is in the booked "times" table or not. IF it is then I want the "Boka" button do disappear. The date shouldn't be able to be added to the "times" table. Alternatively the "date" could disappear entirely from the dates made with Carbon if it is in the "times" table...
I really don't know what to do so I would appreciate som help. Thanks.
And yeah, english isn't my native language so please don't bash me.
There are many ways to validate your data in Laravel. I will show you some of them, feel free to choose the one you'll like.
First of all, the basics.
You can use the validate method in the controller method of your choice. The official documentation has a nice example of it.
...
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
...
Your validation rule goes in the second parameter of the method, the array with other rules.
However, this is not the only way you can deal with validation.
As the documentation says in the "Other Validation Approaches" section, you can:
manually create a validator with Validator::make();
make a FormRequest to isolate your validation rules (and, eventually, logic) in a separate class;
Hope it helps. :)
Just check after validate method that if it returns true or false and based on that use return back with errors or proceed further.
This is probably a really, really simple issue, but it's got me stumped...
So, I've got an article saved in the database with a form, including a field to save a published date. The data entered in this field is successfully saving in the database, along with the rest of the data.
I'm successfully pulling all the saved data back out into the edit form, EXCEPT the published_date field.
I've tried using the same format as the other fields, eg title, both show below
{!! Form::text('title', null) !!}
{!! Form::input('date', 'first_published', null) !!}
This puts dd/mm/yy in the input box, rather than the saved date. If this value isn't changed, the date is saved in the database as today's date.
I've also tried removing the 'date' attribute
{!! Form::input('first_published', null ) !!}
This results in a totally empty box (and no datepicker), which doesn't overwrite the value in the form if not saved. Better, but still not what I want, as I want to show the saved date, which can be changed if required.
I've also tried echoing the $article->published_date in various ways in this field, but only end up with the same results as those above. I can echo out this data elsewhere in the form no problem though using {!! $article->first_published !!}
The form references the model as so:
{!! Form::model($article, ['method' => 'PATCH', 'url' => 'articles'.'/'. $article->id]) !!}
And the relevant controller functions are
//page containing form to edit article, pulls in existing data
public function edit($id)
{
$article = article::findOrFail($id);
return view('articles.edit', compact('article'));
}
//responsible for updating the article record
public function update($id, Request $request)
{
$article = article::findOrFail($id);
$article->update($request->all());
return redirect('articles');
}
The field is set as a timestamp in the migration, and in the model I have
protected $dates = [
'first_published'
];
So, if anyone can shed any light on how to get the saved data value into the form field as in the other fields, it would be much appreciated! :) I'm pretty new to laravel so apologies if there's some blindingly obvious issue I've missed...
On the offchance anyone else has a similar issue - I've now found the solution, which was embarrassingly simple!
I changed the date field as below:
{!! Form::date('first_published', $article->first_published, ['class' => 'nameofclasshere']) !!}
So that the field's default value is the value pulled from my database (which I was able to access elsewhere in the page as detailed in the question). When I submit the form the date remains as the value from the database, unless I change the form value, in which case it's updated.
Don't know if this is the correct or recommended way to do this (and is still different to how I've done the other fields), but it seems to do the trick!
What I did is replaced the Form::input('date', 'published_at', ... line related segment with the following code section (referring to your Laracast Partials and Forms Reuse tutorial) specifically:
<!-- Published_at Form Text Input -->
<div class="form-group">
{!! Form::label('published_at', 'Publish On:') !!}
{!! Form::date('published_at', (isset($article) && $article->published_at ? $article->published_at : date('Y-m-d')), ['class' => 'form-control']) !!}
</div>
In the above replaced code section (isset($article) && $article->published_at ? $article->published_at : date('Y-m-d')) would check if the Form has given an $article object, so then use its existing published_at date or other wise create date with current time and use it.
Hope this would be helpful to somebody out there.
Clearly this question is closed already, but maybe it can help someone.
I was using a form to both edit and create, so I did the following:
<div class="form-group">
<label class="control-label" for="date_">Proyect Date </label>
<input class="form-control" id="datepicker" name="date" placeholder="DD/MM/AA" value="
#if (isset($proyect->date))
{!!date('d-m-Y', strtotime($proyect->date))!!}
#endif" type="text">
I've been trying to fill some textboxes in geckofx 22.0.7. Most of them with success. There are a couple though that resist any change! Both of them allow only numbers to be typed. The first one (the one presented here) is used to receive a date entry. The user only types numbers (not slashes or dashes etc).
The html code follows:
<td class=" dataEntryCol4">
<input id="insertDate" class="ui-inputfield ui-inputmask ui-widget ui-state-default ui-corner-all" type="text" style="width:90px" tabindex="2" value="" name="insertDate" role="textbox" aria-disabled="false" aria-readonly="false" aria-multiline="false">
</td>
My code is this:
GeckoHtmlElement insertDate = document.GetHtmlElementById("insertDate");
insertDate.SetAttribute("value", "08/06/2014");
I also tried using
SendKeys.SendWait("08062014");
SendKeys.SendWait("{TAB}");
I can't get it to work. Any suggestions?
First cast GeckoHtmlElement to a GeckoInputElement then use the Value property.
GeckoInputElement insertDate = (GeckoInputElement)document.GetHtmlElementById("insertDate");
insertDate.Value = "08/06/2014";
Has anyone tried to dynamically select which properties they want to write to an entity on appengine? For example:
I have a web form with 5 fields, and any given user will fill out some subset of those fields. I POST only the fields with data to the server (e.g. Fields 1,2,4). On the server side, how do I elegantly write only properties 1,2, and 4? The Model class has a function that returns a dictionary of property names (Model.properties()), but how would I use it to select property names?
In SQL, I would build an INSERT or UPDATE statement by matching the fields POSTed against the Model.properties() dictionary. I would look at the db module code in the Appengine SDK, to see if the Model class had some collection of Property objects, but I can't find the module on my disk (I'm a little new to python and appengine).
Update: I read trunk/google/appengine/ext/db/init.py which confirmed that there is no way to refer to the properties as a group. Anyone know of a workaround?
Any thoughts?
Update2: This question was answered on the Google Group for AppEngine: http://groups.google.com/group/google-appengine/browse_thread/thread/b50be862f6d94b6e#
The python module will look something like this:
from google.appengine.ext.db import Key
from google.appengine.api.datastore import Get, Put
def edit_item(request, db_id):
objKey = Key(str(db_id))
if request.method == 'POST':
objEntity = Get(objKey)
for k, v in request.POST.iteritems():
objEntity[k]=v
Put(objEntity)
return HttpResponseRedirect('/')
query = TestModel.get(objKey)
return render_to_response('edit.html', ({'modify_data': query,}))
Your HTML should look something like this:
<form method="POST" action="." enctype="multipart/form-data">
Title: <input type="text" name="title" value="{{modify_data.field1}}"/>
Text: <input type="text" name="txt" value="{{modify_data.field2}}"/>
<input type="submit"/>
</form>