I have several answers for a question. My question input filed is like below.
<input name="question" type="text" class="form-control" placeholder="Place your question here">
I am adding multiple answers dynamically. My answer input field is like below.
<input name="answer[]" type="text" class="form-control" placeholder="Place your answer here">
I made question Table using these columns 'id','question','created_at','updated_at'.
I made answer Table using these columns 'id','question_id','answer','created_at','updated_at'.
I am using below code to save Question and Answers.
public function add_form(Request $request)
{
$question = Question::create(['question' => request()->input('question')]);
$question->answers()->create([request()->input('answer')]);
}
I am getting below error.
SQLSTATE[HY000]: General error: 1364 Field 'answer' doesn't have a default value (SQL: insert into `answers` (`question_id`, `updated_at`, `created_at`) values (4, 2021-08-05 11:56:16, 2021-08-05 11:56:16))
First map single dimension array to multidimensional array.
$answer=collect(request()->answer)->transform(function ($item){
return ['answer'=>$item];
})->toArray();
and while saving
$question->answers()->createMany($answer);
Related
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.
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 struggle with the usage of the filter. I have an input field that i want to use as a filter option.
The array looks like this:
$scope.Examples=[
{
name:'Dolly',
place:'roof',
description:'Dolly is a friend of Mike.'
},
{
name:'Mike',
place:'cellar',
decription:'Mike doesn't like the roof.'
},];
$scope.Search="";
The Input:
<input ng-model="Search"
type="text"
placeholder="type something here">
And the ng-repeat:
<tr ng-repeat="something in Examples |filter:Search">
{{something.name}}
</tr>
Now, if i type in "Dolly", he shows me Dolly quite as planned. But if i type in "Mike" the output is Dolly and Mike, because i used the word Mike in the description for Dolly. The same for typing in "roof".
I tried to use
<ng-repeat="something in Examples |filter:{name:'Search'}">
but in that case it simply don't work and there is no output. What i want to do is restrict the filter to 'name' only. Maybe someone have a suggestion how i could make it work.
I'm thankful for every advice.
If you write {name:'Search'} instead of {name:Search}, it means that you keep any string which contains the 'Search' string
Try this :
<ng-repeat="something in Examples |filter:{name:Search}">
I'm trying to implement a form validation using only the view - i'm trying to avoid creating a new directive for this.
Question - is possible to validate matching password only using the partial/view e.g:
div(ng-class="{true: 'no-match'}[password != password2]")
any tip will be gladly appreciated :)
Yes it is possible ,
<input name="password" ng-class = "{valid: (password1 == password2),
invalid: (password1 != password2) }" ng-pattern="/[0-9]/">
where, valid and invalid are css classes,
to display an error message regarding that, use
<div id="invalidEmail" class="mismatch"
ng-show="testForm.password.$error.pattern && !testForm.password.$pristine">
Please enter atleast a number
</div>
where testForm is your form name like
<form name="testForm"> </form>
For more reference you can see the link http://www.ng-newsletter.com/posts/validations.html
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>