I'm writing a simple app for adding and updating information to sqlite3 database using Flask-SQLAlchemy. Now I have a big problem, because I cannot update the database, it just adds a new record every time I submit the form button.
Here is my code:
#main.route("/invoices", methods=["GET", "POST"], defaults={"invoice_id": None})
#main.route("/invoices/<int:invoice_id>", methods=["GET", "POST"])
def invoices(invoice_id):
invoice = None
if invoice_id:
invoice = Invoice.query.get_or_404(invoice_id)
if request.method == "POST":
date = request.form["date"]
name = request.form["name"]
value = request.form["value"]
currency = request.form["currency"]
payment = request.form["payment"]
category = request.form["category"]
description = request.form["description"]
if invoice:
invoice.date = datetime.strptime(date, "%Y-%m-%d")
invoice.name = name
invoice.value = value
invoice.currency = currency
invoice.payment = payment
invoice.category = category
invoice.description = description
else:
invoice = Invoice(
date=datetime.strptime(date, "%Y-%m-%d"),
name=name,
value=value,
currency=currency,
payment=payment,
category=category,
description=description,
)
db.session.add(invoice)
db.session.commit()
return redirect(url_for("main.invoices", invoice_id=invoice.id))
currencies = Currency.query.all()
payments = Payment.query.all()
categories = Category.query.all()
context = {
"invoice_id": invoice_id,
"currencies": currencies,
"payments": payments,
"categories": categories,
"invoice": invoice,
}
return render_template("invoices.html", **context)
I don't know how to update the data, because it always adds a new record, now just commits the existing or changed fields. Maybe something wrong is with my if statements...
Please help me with this task...
Here is the models:
class Invoice(db.Model):
id = db.Column(db.Integer, primary_key=True)
value = db.Column(db.Integer)
date = db.Column(db.DateTime)
name = db.Column(db.String(50))
description = db.Column(db.String(100))
currency = db.Column(db.ForeignKey("currency.id"))
payment = db.Column(db.ForeignKey("payment.id"))
category = db.Column(db.ForeignKey("category.id"))
class Currency(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(10))
class Payment(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
class Category(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(50))
This code may be help to you
#main.route("/invoices", methods=["GET", "POST"], defaults={"invoice_id": None})
#main.route("/invoices/<int:invoice_id>", methods=["GET", "POST"])
def invoices(invoice_id):
invoice = None
if invoice_id is not None:
invoice = Invoice.query.filter_by(id=invoice_id).first()
if request.method == "POST":
date = request.form["date"]
name = request.form["name"]
value = request.form["value"]
currency = request.form["currency"]
payment = request.form["payment"]
category = request.form["category"]
description = request.form["description"]
if invoice is not None:
invoice.date = datetime.strptime(date, "%Y-%m-%d")
invoice.name = name
invoice.value = value
invoice.currency = currency
invoice.payment = payment
invoice.category = category
invoice.description = description
else:
invoice = Invoice(
date=datetime.strptime(date, "%Y-%m-%d"),
name=name,
value=value,
currency=currency,
payment=payment,
category=category,
description=description,
)
db.session.add(invoice)
db.session.commit()
return redirect(url_for("main.invoices", invoice_id=invoice.id))
currencies = Currency.query.all()
payments = Payment.query.all()
categories = Category.query.all()
context = {
"invoice_id": invoice_id,
"currencies": currencies,
"payments": payments,
"categories": categories,
"invoice": invoice,
}
return render_template("invoices.html", **context)
Related
I get an Integrity error, Foreign Key Constraint failed. I have the following function I am trying to run:
if request.method == "POST":
#Get token
access_token = AccessToken.objects.get(token = request.POST.get('access_token'),
expires__gt = timezone.now())
#Get profile
customer = access_token.user.customer
# Check if customer has a order that is not delivered
if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED):
return JsonResponse({"status": "fail", "error": "Your Last Order must be completed"})
# Check Address
if not request.POST["address"]:
return JsonResponse({"status": "failed", "error": "Address is required."})
# Ger Order Details
order_details = json.loads(request.POST["order_details"])
order_total = 0
for meal in order_details:
order_total += Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"]
if len(order_details)>0:
# Step 1 - Create an Order
order = Order.objects.create(
customer = customer,
restaurant_id = request.POST["restaurant_id"],
total = order_total,
status = Order.PENDING,
address = request.POST["address"]
)
# Step 2 - Create Order details
for meal in order_details:
OrderDetails.objects.create(
order = order,
meal_id = meal["meal_id"],
quantity = meal["quantity"],
sub_total = Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"]
)
return JsonResponse({"status": "success"})
Here is my order class:
Class Order(models.Model):
PENDING = 1
COOKING = 2
READY = 3
ONTHEWAY = 4
DELIVERED = 5
STATUS_CHOICES = (
(PENDING, "Pending"),
(COOKING, "Cooking"),
(READY, "Ready"),
(ONTHEWAY, "On The Way"),
(DELIVERED, "Delivered"),
)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE)
driver = models.ForeignKey(Driver, on_delete=models.CASCADE, blank = True, null = True)
address = models.CharField(max_length=500)
total = models.IntegerField()
status = models.IntegerField(choices = STATUS_CHOICES)
created_at = models.DateTimeField(default = timezone.now)
picked_at = models.DateTimeField(blank = True, null = True)
def __str__(self):
return str(self.id)
I previously got an error because Driver was not null so I added blank = True, null = True. Now it gives the Foreign Key Contraint Error.
I am testing the function is postman, and I do not define the driver anywhere, the driver is to be added later not while the function is called.
This is my views.py
def restaurant_add_meal(request):
form = MealForm()
if request.method == "POST":
form = MealForm(request.POST, request.FILES)
if form.is_valid():
meal = form.save(commit=False)
meal.restaurant = request.user.restaurant
meal.save()
return redirect(restaurant_meal)
return render(request, 'restaurant/add_meal.html', {
"form": form
})
I changed restaurant_id = request.POST["restaurant_id"] to
restaurant = Restaurant.objects.get(pk = request.POST["restaurant_id"])
and the error is fixed.
I have two tables, named projects and actions and every project contain several action
class Projet(db.Model):
__tablename__ = 'projets'
id = db.Column(db.Integer, primary_key=True)
nom_projet = db.Column(db.String(100))
description_projet = db.Column(db.String(800))
date_affectation = db.Column(db.DateTime, nullable = False)
statut_projet = db.Column(db.String(100))
admin_id = db.Column(db.Integer, db.ForeignKey('admins.id'))
actions = db.relationship('Action', backref='projet',
lazy='dynamic')
def __repr__(self):
return '<Projet: {}>'.format(self.id)
class Action(db.Model):
__tablename__ = 'actions'
id = db.Column(db.Integer, primary_key=True)
projet_id = db.Column(db.Integer, db.ForeignKey('projets.id'))
description = db.Column(db.String(1000))
statut_action = db.Column(db.String(100))
date_action = db.Column(db.DateTime, nullable = False)
date_execution = db.Column(db.DateTime, nullable = True)
def __repr__(self):
return '<Action: {}>'.format(self.id)
my problem is, I need to create a new action based on an existing project as shown in image,
I need to click on add button and he must redirect me to action form with the name of project auto-selected, and I entre the action details.
this is my first code to add action:
#auth.route('/action/add', methods=['GET', 'POST'])
#login_required
def add_action():
form = ActionForm()
if form.validate_on_submit():
action = Action(
projet = form.projet.data,
description = form.description.data,
statut_action = form.statut_action.data,
date_action = form.date_action.data,
date_execution = form.date_execution.data
)
try:
db.session.add(action)
db.session.commit()
flash('You have successfully added a new action.')
except:
flash('Error: action name already exists.')
return redirect(url_for('auth.list_projets'))
return render_template('admin/actions/action.html', action="Add", form=form,
title="ADD ACTION")
Steps:
Update the URL to include project_id as path param: ex: /project/1/actions/add is meant to load a page with new action form for project with id 1
Update the links to add new action in the previous page(as shown in the screenshot) as per step 1
Remove project field from ActionForm as it is handled using path param
Update "new action form" page to show product name coming in product_name variable
Try,
#auth.route('/project/<project_id>/action/add', methods=['GET', 'POST'])
#login_required
def add_action(project_id):
form = ActionForm()
project = Project.query.get(project_id)
if not project:
flash('Error: invalid project')
abort(404)
if form.validate_on_submit():
action = Action(
project = project,
description = form.description.data,
statut_action = form.statut_action.data,
date_action = form.date_action.data,
date_execution = form.date_execution.data
)
try:
db.session.add(action)
db.session.commit()
flash('You have successfully added a new action.')
except:
flash('Error: action name already exists.')
return redirect(url_for('auth.list_projets'))
return render_template('admin/actions/action.html', action="Add", form=form,
title="ADD ACTION", project_name=project.name)
I am using Python library flask-rest-jsonapi to design an API. The library uses flask-sqlalchemy and marshmallow. Marshmallow has a requirement to have an "id" and a "type" field mandatory in the schema.
The database tables that I am designing APIs for doesn't have "id" column. The two tables that I am trying to define the relationship are called Department and Teacher where one department has multiple teachers so there is one to many relationship between department and teacher. Their primary keys columns are called "Department_Unique_ID" and "Teacher_Unique_ID".
Here is my code:
from flask import Flask
from flask_rest_jsonapi import Api, ResourceDetail, ResourceList, ResourceRelationship
from flask_rest_jsonapi.exceptions import ObjectNotFound
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
from marshmallow_jsonapi.flask import Schema, Relationship
from marshmallow_jsonapi import fields
import connectDB
# Create the Flask application
app = Flask(__name__)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app = connectDB.connectToDb(app)
db = SQLAlchemy(app)
class Department(db.Model):
db.Model.metadata.schema = 'UNIVERSITY'
__tablename__ = 'Department'
Department_Unique_ID = db.Column(db.String, primary_key=True)
Department_Name = db.Column(db.String)
uni_teacher = db.relationship('Teacher', backref=db.backref('Department'))
__mapper_args__ = {
"order_by":Department_Unique_ID
}
class Teacher(db.Model):
db.Model.metadata.schema = 'UNIVERSITY'
__tablename__ = 'Teacher'
Teacher_Unique_ID = db.Column(db.String, primary_key=True)
Teacher_Name = db.Column(db.String)
Department_ID_Unique = db.Column(db.String, db.ForeignKey('Department.Department_Unique_ID'))
__mapper_args__ = {
"order_by":Teacher_Unique_ID
}
class DepartmentSchema(Schema):
class Meta:
type_ = 'uni_department'
self_view = 'uni_department_detail'
self_view_kwargs = {'id': '<Department_Unique_ID>'}
self_view_many = 'uni_department_list'
strict = True
__model__ = Department
id = fields.Integer(as_string=True, many=True, dump_only=True) #not used, if I remove this, I get an error "Must have an 'id' field"
Department_Unique_ID = fields.Str()
Department_Name = fields.Str()
uni_teacher = Relationship(self_view='uni_department_uni_teacher',
self_view_kwargs={'id':'<Department_Unique_ID>'},
related_view='uni_teacher_list',
related_view_kwargs={'id':'<Department_Unique_ID>'},
many=True,
schema='TeacherSchema',
type_='uni_teacher',
id_field='Teacher_Unique_ID')
class TeacherSchema(Schema):
class Meta:
type_ = 'uni_teacher'
self_view = 'uni_teacher_detail'
self_view_kwargs = {'id': '<Teacher_Unique_ID>'}
self_view_many = 'uni_teacher_list'
strict = True
__model__ = Teacher
id = fields.Integer(as_string=True, many=True, dump_only=True) #not used, if I remove this, I get an error "Must have an 'id' field"
Teacher_Unique_ID = fields.Str()
Teacher_Name = fields.Str()
owner = Relationship(attribute='uni_department',
self_view='uni_teacher_uni_department',
self_view_kwargs={'id':'<Teacher_Unique_ID>'},
related_view='uni_department_detail',
related_view_kwargs={'id':'<Department_Unique_ID>'},
schema='DepartmentSchema',
type_='uni_department')
class DepartmentList(ResourceList):
schema = DepartmentSchema
data_layer = {'session': db.session,
'model': Department}
class TeacherList(ResourceList):
def query(self, view_kwargs):
query_ = self.session.query(Teacher)
if view_kwargs.get('Teacher_Unique_ID') is not None:
try:
self.session.query(Department).filter_by(Teacher_Unique_ID=view_kwargs['Teacher_Unique_ID']).one()
except NoResultFound:
raise ObjectNotFound({'parameter': 'Teacher_Unique_ID'}, "Teacher: {} not found".format(view_kwargs['Teacher_Unique_ID']))
else:
query_ = query_.join(Department).filter(Department.id == view_kwargs['Teacher_Unique_ID'])
return query_
def before_create_object(self, data, view_kwargs):
if view_kwargs.get('Teacher_Unique_ID') is not None:
uni_department = self.session.query(Department).filter_by(Teacher_Unique_ID=view_kwargs['Department_Unique_ID']).one()
data['Department_Unique_ID'] = uni_department.Department_Unique_ID
schema = TeacherSchema
data_layer = {'session': db.session,
'model': Teacher}
class DepartmentDetail(ResourceDetail):
def before_get_object(self, view_kwargs):
if view_kwargs.get('Teacher_Unique_ID') is not None:
try:
uni_teacher = self.session.query(Teacher).filter_by(Department_Unique_ID=view_kwargs['Department_Unique_ID']).one()
except NoResultFound:
raise ObjectNotFound({'parameter': 'Department_Unique_ID'},
"Teacher: {} not found".format(view_kwargs['Department_Unique_ID']))
else:
if uni_teacher.uni_department is not None:
view_kwargs['Department_Unique_ID'] = uni_teacher.uni_department.Department_Unique_ID
else:
view_kwargs['Department_Unique_ID'] = None
schema = DepartmentSchema
data_layer = {'session': db.session,
'model': Department}
class TeacherDetail(ResourceDetail):
schema = TeacherSchema
data_layer = {'session': db.session,
'model': Teacher}
class DepartmentRelationship(ResourceRelationship):
schema = DepartmentSchema
data_layer = {'session': db.session,
'model': Department}
class TeacherRelationship(ResourceRelationship):
schema = TeacherSchema
data_layer = {'session': db.session,
'model': Teacher}
api = Api(app)
api.route(DepartmentList, 'uni_department_list', '/uni_department')
api.route(TeacherList, 'uni_teacher_list', '/uni_teacher', '/uni_teacher/<int:Department_Unique_ID>/uni_teacher')
api.route(DepartmentDetail, 'uni_department_detail', '/uni_department/<int:Department_Unique_ID>', '/uni_teacher/<int:Department_ID_Unique>/owner')
api.route(TeacherDetail, 'uni_teacher_detail', '/uni_teacher/<int:Teacher_Unique_ID>')
api.route(DepartmentRelationship, 'uni_department_uni_teacher', '/uni_department/<int:Department_Unique_ID>/relationships/uni_teacher')
api.route(TeacherRelationship, 'uni_teacher_uni_department', '/uni_teacher/<int:Teacher_Unique_Department>/relationships/owner')
if __name__ == '__main__':
# Start application
app.debug = True
app.run()
I am following the example from flask-rest-jsonapi. Any help would be appreciated.
EDIT1- Here is the connectDB.py code as requested-
import yaml
def readDbDetails():
with open('database_config.yaml', 'r') as stream:
return (yaml.load(stream))
dbDetails = readDbDetails()
def connectToDb(app):
database_host = dbDetails['database_host']
database_username = dbDetails['database_username']
database_name = dbDetails['database_name']
database_password = dbDetails['database_password']
database_port = dbDetails['database_port']
print(database_host)
print(database_name)
print(database_username)
print(database_password)
print(database_port)
app.config[
'SQLALCHEMY_DATABASE_URI'] = 'mssql+pymssql://'+database_username+':'+database_password+'#'+database_host+':'+database_port+'/'+database_name+''
return app
You can use attribute property and assign the primary key to that id field
class DepartmentSchema(Schema):
class Meta:
type_ = 'uni_department'
self_view = 'uni_department_detail'
self_view_kwargs = {'id': '<Department_Unique_ID>'}
self_view_many = 'uni_department_list'
strict = True
__model__ = Department
id = fields.Integer(attribute='Department_Unique_ID', as_string=True, many=True, dump_only=True)
Department_Unique_ID = fields.Str()
Department_Name = fields.Str()
uni_teacher = Relationship(self_view='uni_department_uni_teacher',
self_view_kwargs={'id': '<Department_Unique_ID>'},
related_view='uni_teacher_list',
related_view_kwargs={'id': '<Department_Unique_ID>'},
many=True,
schema='TeacherSchema',
type_='uni_teacher',
id_field='Teacher_Unique_ID')
class TeacherSchema(Schema):
class Meta:
type_ = 'uni_teacher'
self_view = 'uni_teacher_detail'
self_view_kwargs = {'id': '<Teacher_Unique_ID>'}
self_view_many = 'uni_teacher_list'
strict = True
__model__ = Teacher
id = fields.Integer(attribute='Teacher_Unique_ID', as_string=True, many=True, dump_only=True)
Teacher_Unique_ID = fields.Str()
Teacher_Name = fields.Str()
owner = Relationship(attribute='uni_department',
self_view='uni_teacher_uni_department',
self_view_kwargs={'id': '<Teacher_Unique_ID>'},
related_view='uni_department_detail',
related_view_kwargs={'id': '<Department_Unique_ID>'},
schema='DepartmentSchema',
type_='uni_department')
I have three related SQLAlchemy models in my flask-admin application (simplified):
class Client(db.Model, BasicMixin, ActiveMixin, TimestampMixin):
id = db.Column(UUIDType, primary_key=True, default=uuid.uuid4)
title = db.Column(db.String(1000))
issues = db.relationship('Issue', backref='client', cascade='all, delete-orphan')
class Issue(db.Model, BasicMixin, ActiveMixin, TimestampMixin):
id = db.Column(UUIDType, primary_key=True, default=uuid.uuid4)
date = db.Column(db.Date, default=datetime.date.today())
client_id = db.Column(UUIDType, db.ForeignKey('clients.id'), nullable=False)
articles = db.relationship('Article', backref='issue', cascade='all, delete-orphan')
class Article(db.Model, BasicMixin, TimestampMixin):
id = db.Column(UUIDType, primary_key=True, default=uuid.uuid4)
title = db.Column(db.String())
body = db.Column(db.String())
issue_id = db.Column(UUIDType, db.ForeignKey('issues.id'), nullable=False)
Client has many Issues, each Issue has many Articles.
I also have a ModelView for Article in which I should be able to filter list of Articles by Client (select Client by name and show Articles belonging to this Client only). What should I do to create such a filter in flask-admin?
Here's a single-file example using SQLite:
Mostly straightforward Flask, SQLalchemy and Flask-Admin. The class of interest is FilterByClientTitle.
class FilterByClientTitle(BaseSQLAFilter):
# Override to create an appropriate query and apply a filter to said query with the passed value from the filter UI
def apply(self, query, value, alias=None):
return query.join(Article.issue).join(Issue.client).filter(Client.title == value)
# readable operation name. This appears in the middle filter line drop-down
def operation(self):
return u'equals'
# Override to provide the options for the filter - in this case it's a list of the titles of the Client model
def get_options(self, view):
return [(client.title, client.title) for client in Client.query.order_by(Client.title)]
The view for the Article model has a couple of important settings/overrides:
class ArticleView(BaseAdminView):
# ......
# No need to specify the column as we'll set the SQLalchemy filter directly in the filter's apply method
column_filters = [FilterByClientTitle(column=None, name='Client Title')]
# Need this so the filter options are always up-to-date
#expose('/')
def index_view(self):
self._refresh_filters_cache()
return super(ArticleView, self).index_view()
Here's the complete example, requires the faker library for the random data:
import datetime
from flask import Flask, url_for
from flask_admin.contrib.sqla import ModelView
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin, expose
from faker import Faker
from flask_admin.contrib.sqla.filters import BaseSQLAFilter
from markupsafe import Markup
app = Flask(__name__)
# Create dummy secrey key so we can use sessions
app.config['SECRET_KEY'] = '123456790'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sample_db.sqlite'
db = SQLAlchemy(app)
#app.route('/')
def index():
return 'Click me to get to Admin!'
class Client(db.Model):
__tablename__ = 'clients'
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String(1000))
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return self.title
class Issue(db.Model):
__tablename__ = 'issues'
id = db.Column(db.Integer(), primary_key=True)
date = db.Column(db.Date, default=datetime.date.today())
client_id = db.Column(db.Integer(), db.ForeignKey('clients.id'), nullable=False)
client = db.relationship(Client, backref=db.backref('issues', uselist=True, cascade='all, delete-orphan'))
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return unicode(self.date)
class Article(db.Model):
__tablename__ = 'articles'
id = db.Column(db.Integer(), primary_key=True)
title = db.Column(db.String())
body = db.Column(db.String())
issue_id = db.Column(db.Integer(), db.ForeignKey('issues.id'), nullable=False)
issue = db.relationship(Issue, backref=db.backref('articles', uselist=True, cascade='all, delete-orphan'))
def __str__(self):
return unicode(self).encode('utf-8')
def __unicode__(self):
return '{title} ... {body} ...'.format(title=self.title[:30], body=self.body[:30])
class BaseAdminView(ModelView):
can_view_details = True
named_filter_urls = True
class ClientView(BaseAdminView):
column_list = ('id', 'title')
column_default_sort = ('title', False)
column_filters = ['id', 'title']
class IssueView(BaseAdminView):
column_list = ('id', 'date', 'articles')
column_default_sort = ('date', False)
column_filters = ['id', 'date']
column_formatters = {
'articles': lambda v, c, m, n: Markup('<br>'.join([unicode(a) for a in m.articles])),
}
class FilterByClientTitle(BaseSQLAFilter):
# Override to create an appropriate query and apply a filter to said query with the passed value from the filter UI
def apply(self, query, value, alias=None):
return query.join(Article.issue).join(Issue.client).filter(Client.title == value)
# readable operation name. This appears in the middle filter line drop-down
def operation(self):
return u'equals'
# Override to provide the options for the filter - in this case it's a list of the titles of the Client model
def get_options(self, view):
return [(client.title, client.title) for client in Client.query.order_by(Client.title)]
class ArticleView(BaseAdminView):
column_list = ('title', 'body', 'issue', 'issue.client')
column_labels = {
'issue': 'Issue Date',
'issue.client': 'Client Title'
}
column_default_sort = ('title', False)
def issue_link(self, context, model, name):
return Markup('{date}'.format(
url=url_for('issue.index_view', flt1_id_equals=model.issue.id),
date=model.issue.date)
)
def client_link(self, context, model, name):
return Markup('{title}'.format(
url=url_for('client.index_view', flt1_id_equals=model.issue.client.id),
title=model.issue.client.title)
)
# Display Issue Date and Client Title as links back to their filtered views
column_formatters = {
'title': lambda v, c, m, n: '{} ...'.format(m.title[:20]),
'body': lambda v, c, m, n: '{} ...'.format(m.body[:40]),
'issue': issue_link,
'issue.client': client_link,
}
# No need to specify the column as we'll set the SQLalchemy filter directly in the filter's apply method
column_filters = [FilterByClientTitle(column=None, name='Client Title')]
# Need this so the filter options are always up-to-date
#expose('/')
def index_view(self):
self._refresh_filters_cache()
return super(ArticleView, self).index_view()
admin = Admin(app, template_mode="bootstrap3")
admin.add_view(ClientView(Client, db.session))
admin.add_view(IssueView(Issue, db.session))
admin.add_view(ArticleView(Article, db.session))
def build_sample_db():
fake = Faker()
number_of_clients = 100
number_of_issues_per_client = 5
number_of_articles_per_issues = 5
db.drop_all()
db.create_all()
clients = []
issues = []
articles = []
for client_counter in range(0, number_of_clients):
client_title = fake.last_name()
clients.append({
'id': client_counter,
'title': client_title
})
for issue_counter in range(0, number_of_issues_per_client):
issue_id = number_of_issues_per_client * client_counter + issue_counter
issues.append({
'id': issue_id,
'client_id': client_counter,
'date': fake.date_time_this_decade(before_now=True, after_now=False, tzinfo=None)
})
for article_counter in range(0, number_of_articles_per_issues):
articles.append({
'id': (number_of_articles_per_issues * issue_id) + article_counter,
'issue_id': issue_id,
'title': '{} - {}'.format(client_title, fake.catch_phrase()),
'body': '{} - {}'.format(client_title, fake.text(max_nb_chars=200))
})
db.session.bulk_insert_mappings(Client, clients)
db.session.bulk_insert_mappings(Issue, issues)
db.session.bulk_insert_mappings(Article, articles)
db.session.commit()
if __name__ == '__main__':
build_sample_db()
app.run(debug=True)
I am trying to save the current time in my database when I save a review but each time It stores the time as 1990. When I run datetime.utcnonw() on the python shell it returns the correct date. What am I doing wrong?
Here is the code for my model
class Review(db.Model):
__tablename__ = 'reviews'
dates = datetime.now()
id = db.Column(db.Integer,primary_key = True)
movie_id = db.Column(db.Integer)
movie_title = db.Column(db.String)
image_path = db.Column(db.String)
movie_review = db.Column(db.String)
posted = db.Column(db.DateTime(),default=datetime.utcnow)
user_id = db.Column(db.Integer,db.ForeignKey("users.id"))
Here is the code inserting it into the database
#main.route('/movie/review/new/<int:id>', methods = ['GET','POST'])
#login_required
def new_review(id):
form = ReviewForm() #wtf form class that has only two fields
movie = get_movie(id) # Function that calls an api and returns a movie
if form.validate_on_submit():
title = form.title.data
review = form.review.data
new_review = Review(movie_id=movie.id,movie_title=title,image_path=movie.poster,movie_review=review,user=current_user)
new_review.save_review()
return redirect(url_for('.movie',id = movie.id ))