python ORM table insert 0 instead of none - python

Here is much of my code. My real question is in models.py, countCurrentOccupancy(): I have a work-around where I need current_occupancy to be 0 when a new Shelter is created. Is there a better way of doing this? Default values don't seem to work, passing 0 from the views.py doesn't seem to work either. Nor does inserting a 0 in the methods.py.
dbsetup.py
class Shelter(Base):
"""Connects to the Shelter table
"""
__tablename__ = 'shelter'
shelter_id = Column(Integer, primary_key = True)
name = Column(String(50), nullable = False)
address = Column(String(30))
city = Column(String(20))
state = Column(String(13))
zipCode = Column(Integer(5))
website = Column(String)
maximum_capacity = Column(Integer, nullable = False)
current_occupancy = Column(Integer, default = '0')
remaining_spaces = Column(Integer)
models.py:
def createShelter(new_shelter):
newShelter = Shelter(
name = new_shelter['name'],
address = new_shelter['address'],
city = new_shelter['city'],
state = new_shelter['state'],
zipCode = new_shelter['zipCode'],
website = new_shelter['website'],
maximum_capacity = new_shelter['maximum_capacity'],
current_occupancy = 0)
session.add(newShelter)
session.commit()
#This method returns current_occupancy from the Shelter table as a list of only current_occupancy values
def countUpdatedOccupancy():
p = session.query(Shelter.shelter_id, Shelter.current_occupancy)
w = []
for row in p:
w.append(row[1])
return w
#This method updates Shelter.current_occupancy with the countCurrentOccupancy().
def updateCurrentOccupancy():
counts_list = countCurrentOccupancy()
counts_dict = dict(counts_list)
shelters = session.query(Shelter)
for shelter in shelters:
shelter.current_occupancy = counts_dict.get(shelter.shelter_id)
co = 0
if shelter.current_occupancy is None:
co = 0
else:
co = shelter.current_occupancy
shelter.remaining_spaces = shelter.maximum_capacity - co
session.add(shelter)
session.commit()
views:
#app.route('/shelters/shelternew', methods = ['GET','POST'])
def shelterNew():
form = forms.ShelterForm()
if request.method == "POST":
new_shelter = {
'name': form.name.data,
'address': form.address.data,
'city': form.city.data,
'state': form.state.data,
'zipCode': form.zipCode.data,
'website': form.website.data,
'maximum_capacity': form.maximum_capacity.data}
models.createShelter(new_shelter)
flash('A new shelter has been opened!')
return redirect(url_for('shelters'))
else:
return render_template('shelterNew.html', form = form)

Related

having trouble make foreign id column point to already existing row flask python

So on the /join page, I am trying to add a person with an email to a team that is in the Team_name database that already exists. every time I try something it just creates a new row in the team_name column, but I want team_name_id of the name and email the person submits the /join page to point back to an already existing team in team_name column.
from distutils.command.sdist import sdist
from enum import unique
from turtle import back
from flask import Flask, redirect, render_template, session, url_for, request, flash
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from sqlalchemy import ForeignKey, select
from datetime import datetime
import sqlite3
from flask import g
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI']= 'sqlite:///test.db'
db = SQLAlchemy(app)
#app.config['SQLALCHEMY_TRACK_MODIFICATIONS']= True
app.config['SECRET_KEY'] = 'sdafwer3rw93ur9wu0er339d'
class Forms(db.Model):
__tablename__ = 'forms'
id = db.Column(db.Integer, primary_key = True)
names = db.Column(db.String(200), nullable = False)
emails = db.Column(db.String(200))
team_name_id = db.Column(db.Integer, db.ForeignKey('team_names.id'))
def __repr__(self):
return '<Forms %r>' % self.id
def __init__(self, names, emails, team_names):
self.names = names
self.emails = emails
self.team_names = team_names
class Team_names(db.Model):
__tablename__ = 'team_names'
id = db.Column(db.Integer, primary_key = True)
team_name = db.Column(db.String(200), unique = True)
formss = db.relationship('Forms', backref = 'team_names', lazy='dynamic')
def __repr__(self):
return '<Team_names %r>' % self.id
def __init__(self, team_name):
self.team_name = team_name
#app.route('/', methods=['POST','GET'])
def first():
return render_template('first.html')
#app.route('/new', methods=['POST','GET'])
def new():
if request.method == 'POST':
givenname = request.form['names']
givenemail = request.form['emails']
giventeamnames = request.form['team_names']
adding1 = Team_names(team_name = giventeamnames)
adding = Forms(names = givenname, emails = givenemail, team_names=adding1)
try:
db.session.add(adding)
db.session.add(adding1)
db.session.commit()
return render_template('thankyou.html')
except:
return 'There was an error adding your team please try again or team name was not unique'
else:
return render_template('new.html')
#app.route('/join', methods=['POST','GET'])
def join():
teams = Team_names.query.with_entities(Team_names.team_name)
for team in teams:
team = Team_names.team_name
if request.method == 'POST':
givennames = request.form['names']
givenemails = request.form['emails']
select = request.form('selected_class')
adding1 = Team_names(team_name= select)
adding = Forms(names = givennames, emails = givenemails, team_names=adding1 )
try:
db.session.add(adding)
db.session.commit()
return render_template('thankyou.html')
except:
return str(print(select))
#'There was an error join your team please try again'
else:
return render_template("join.html", teams=teams)
if __name__ == "__main__":
app.run(debug=True)
<select id="team_names" name="selected_class" placeholder="Select your groups team name" class="text-box" required><br><br>
{% for team in teams %}
<OPTION value={{team[0]}}>{{team[0]}}</OPTION>
{% endfor %}</select><br><br>
Try this.
Replace:
adding1 = Team_names(team_name= select)
adding = Forms(names = givennames, emails = givenemails, team_names=adding1 )
with:
selected_team = db.session.query(Team_names).filter(Team_names.team_name == select).first()
adding = Forms(names = givennames, emails = givenemails, team_names = selected_team)
In your original adding1 you are creating a new team based on the selected value. The proposed fix has SQLA grab a team object based on the selected value.

Django manytomany field holding Users autofilling

I am pulling data from a json file on the web, and updating it in my django database. I want to keep track of users that are associated with each team, but as soon as a user loads the page once they are added to the model. How do I avoid this?
class Team(models.Model):
name = models.CharField(max_length=120)
abbreviation = models.CharField(max_length=3)
id = models.IntegerField(primary_key=True)
link = models.CharField(max_length=120)
wins = models.IntegerField(default=0)
losses = models.IntegerField(default=0)
ties = models.IntegerField(default=0)
points = models.IntegerField(default=0)
users = models.ManyToManyField(User)
def getTeams():
import requests
baseUrl = "https://statsapi.web.nhl.com/"
# INITALIZING THE DATA IN THE DATA DICTIONARY
r = requests.get(baseUrl + '/api/v1/teams')
originalData = r.json()
# i dont need the copyright, only care about the teams
originalData = originalData["teams"]
for team in originalData:
id = team["id"]
try:
databaseTeam = Team.objects.get(id = id)
except Exception:
Team.objects.create(id = id)
databaseTeam = Team.objects.get(id = id)
databaseTeam.name = team["name"]
databaseTeam.abbreviation = team["abbreviation"]
databaseTeam.link = team["link"]
databaseTeam.save()
print("done")
#login_required
def myTeamView(request):
t1 = Thread(target=getTeams)
t1.start()
return(render(request, "teams/myTeams.html", {}))
The user is stored on user variable inside the request, so first we need to pass it to getTeams method. Then we use the method add of Manytomany fields to append an record to it, in this case the user.
def getTeams(request):
import requests
baseUrl = "https://statsapi.web.nhl.com/"
# INITALIZING THE DATA IN THE DATA DICTIONARY
r = requests.get(baseUrl + '/api/v1/teams')
originalData = r.json()
# i dont need the copyright, only care about the teams
originalData = originalData["teams"]
for team in originalData:
id = team["id"]
try:
databaseTeam = Team.objects.get(id = id)
except Exception:
Team.objects.create(id = id)
databaseTeam = Team.objects.get(id = id)
databaseTeam.name = team["name"]
databaseTeam.abbreviation = team["abbreviation"]
databaseTeam.link = team["link"]
databaseTeam.save()
databaseTeam.users.add(request.user) # after save!!
print("done")
#login_required
def myTeamView(request):
t1 = Thread(target=getTeams, args=(request, ))
t1.start()
return(render(request, "teams/myTeams.html", {}))

Python - Create/Read/Update/Delete records in NetSuite

I was wondering how to Create/Read/Update/Delete records and their standard/custom fields, using python SOAP with NS WSDL
Here's a script that gives an example on how to login, and then to CRUD the records in NetSuite.
from zeep import Client
WSDL_URL = 'https://webservices.netsuite.com/wsdl/v2017_2_0/netsuite.wsdl' #WSDL we're using (don't change)
NS_EMAIL= 'NSemail#email.com' #NS-Email
NS_PASSWORD = 'NSPassword' #NS-Password
NS_ROLE = 'NSroleId' #NS-Role Id
NS_ACCOUNT = 'NSaccountId' #NS-Account Id
NS_APPID = 'NS268FD3-8553-4464-AEEB-FB6BE2EE616E' #NS App-ID
def make_app_info(client): #make app info, used in login_client
AppInfo = client.get_type('ns4:ApplicationInfo')
app_info = AppInfo(applicationId = NS_APPID)
return app_info
def make_passport(client): #make passport, used in login_client
RecordRef = client.get_type('ns0:RecordRef')
Passport = client.get_type('ns0:Passport')
role = RecordRef(internalId=NS_ROLE)
return Passport(email=NS_EMAIL,
password=NS_PASSWORD,
account=NS_ACCOUNT,
role=role)
def login_client(): #login
client = Client(WSDL_URL)
login = client.service.login(passport=make_passport(client), _soapheaders={'applicationInfo': make_app_info(client)}, )
return client
def add_customer(): #add a customer, example
client = login_client()
RecordRef = client.get_type('ns0:RecordRef') #set RecordRef as a RecordReference
StringCustomFieldRef = client.get_type('ns0:StringCustomFieldRef') #custom string field ref
CustomFieldList = client.get_type('ns0:CustomFieldList') #translator for custom field list
#customField acctName
acctName = StringCustomFieldRef() #this custom field is a string
acctName.internalID = '1569'
acctName.scriptId = 'custentity_sf_account_name'
acctName.value = 'Test data'
#customField acctId
acctID= StringCustomFieldRef()
acctID.internalId= '1596'
acctID.scriptId= 'custentity_account_id'
acctID.value = 'More Test data'
Customer = client.get_type('ns13:Customer') #make customer of type Customer
customer = Customer( #set customer
companyName='TEST',
entityId='TEST (US LLC)',
subsidiary = RecordRef(internalId='5', type='subsidiary'), #subsidiary is a RecordRef field, so you need to use RecordRef
customFieldList = CustomFieldList([acctID,acctName]) #set custom Fields
)
response = client.service.add(customer) #make the call
print(response)
def get_customer(id): #fetch customer
client = login_client()
Record = client.get_type('ns0:RecordRef') #set Record = to RecordReference
record = Record(internalId=id, type='customer') #change type for different type searches
response = client.service.get(record)
r = response.body.readResponse
#print(r) #detailed view
if r.status.isSuccess:
print(r.record) #r.record.companyName #simple view
def update_customer(): #update a customer
client = login_client()
Customer = client.get_type('ns13:Customer') #set Customer = to NS customer type
customer = Customer(
internalId = '451348', #must specify internalId
companyName='Testing 123'
)
response = client.service.update(customer) #upsert can also be used
print(response)
def delete_customer(id): #delete
client = login_client()
Record = client.get_type('ns0:RecordRef') #set Record to RecordReference
record = Record(internalId=id, type='customer')
response = client.service.delete(record) #run command
print(response)
def add_order(): #add an order
client = login_client()
RecordRef = client.get_type('ns0:RecordRef')
SelectCustomFieldRef = client.get_type('ns0:SelectCustomFieldRef')
StringCustomFieldRef = client.get_type('ns0:StringCustomFieldRef')
CustomFieldList = client.get_type('ns0:CustomFieldList')
SalesOrderItemList = client.get_type('ns19:SalesOrderItemList')
Order = client.get_type('ns19:SalesOrder')
SalesOrderItem = client.get_type('ns19:SalesOrderItem')
billtier = SelectCustomFieldRef() #using SelectCustomFieldRef since custom field is a select
billtier.internalId = '308' #custField InternalId
billtier.scriptId = 'custbody_bill_to_tier' #custField scriptId
billtier.value ={
'internalId': '2', #option ID
'externalId': None,
'typeId': '12' #list Id
}
item1 = SalesOrderItem() #making a single lineitem
item1.quantity = '1'
item1.item = RecordRef(internalId='5816')
item1.amount = 999
order = Order(
entity = RecordRef(internalId='451656', type='customer'),
itemList= SalesOrderItemList([item1]), #Add the line item
customFieldList = CustomFieldList([billtier]) #add the custom fields
)
response = client.service.add(order) #add the order
print(response)
Some Notes:
In cases where it says: RecordRef = client.get_type('ns0:RecordRef')
the ns0 refers to the namespace .xsd file that is in the import section on the wsdl.
A list of all NetSuite objects and their fields can be found here: http://www.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2016_1/schema/other/salesorderitemlist.html?mode=package
Details about field references to use when handling different types of custom fields:
https://system.na1.netsuite.com/app/help/helpcenter.nl?fid=section_n3458179.html

Django: update isn't saving the record to the database

def registrar(request):
form = RegForm(request.POST or None)
context = {
"form":form
}
if request.method == 'POST':
form = RegForm(request.POST)
if form.is_valid():
b = form.cleaned_data['folioboleto']
n = form.cleaned_data['nombre']
aP = form.cleaned_data['apellidoPaterno']
aM = form.cleaned_data['apellidoMaterno']
fecha = form.cleaned_data['fechaDeNacimiento']
g = form.cleaned_data['genero']
e = form.cleaned_data['email']
tel = form.cleaned_data['telefono']
di = form.cleaned_data['direccion']
c = form.cleaned_data['ciudad']
est = form.cleaned_data['estado']
actP = form.cleaned_data['actividadPrincipal']
cSE = form.cleaned_data['comoSupoEvento']
aF = form.cleaned_data['aceptoFotos']
obj = Cliente.objects.create(Nombre=n,ApellidoPaterno=aP,ApellidoMaterno=aM,FechaDeNacimiento=fecha,Genero=g,Email=e,Telefono=tel,Direccion=di,Ciudad=c,Estado=est,ActividadPrincipal=actP,ComoSupoEvento=cSE,AceptoFotos=aF)
bole = Boleto.objects.get(Folio=b)
if bole.Folio == b:
bole.Estatus = '2'
bole.Cliente_id = obj.id
bole.save(update_fields=['Estatus'])
The object bole save method isn't saving the changes to the database.
I believe your problem is with bole.save(update_fields=['Estatus']), which would only update the field named Estatus, which doesn't seem to be being set. Try just using a bare save instead:
bole.save()
Good luck!

App Engine, Python: problem updating datastore record

I need to update a record in the datastore, but instead of updated record I get always a new record.
My model:
class PageModel(db.Model):
title = db.StringProperty()
content = db.TextProperty()
reference = db.SelfReferenceProperty()
user = db.UserProperty(auto_current_user = True)
created = db.DateTimeProperty(auto_now_add = True)
modified = db.DateTimeProperty(auto_now = True)
type = db.StringProperty()
template = db.StringProperty()
position = db.IntegerProperty()
hidden = db.BooleanProperty()
historical = db.BooleanProperty()
My handler:
class EditHandler(webapp.RequestHandler):
def post(self):
if self.request.path[6:] == '':
page_id = 8
else:
page_id = int(self.request.path[6:]) # path: /edit/35
#id = self.request.get('id')
CP = PageModel.get_by_id(int(page_id))
key = CP.key()
title = self.request.get('title')
content = self.request.get('content')
type = self.request.get('type')
hidden = self.request.get('hidden')
#position = self.request.get('type')
reference = PageModel.get_by_id(int(self.request.get('reference')))
template = self.request.get('template')
if ".htm" not in template:
template = "index.htm"
#if title == '' or content == '':
#doRender(self,'create_page.htm',{'error' : 'Please fill in all fields'} )
#return
#edited_page = PageModel(key=CP.key, title=title, content=content, type=type, reference=reference, template=template)
edited_page = PageModel()
edited_page.key = CP.key()
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()
There should be something wrong with edited_page.key = CP.key(), or what?!
Why are you created a new PageModel everytime? instead edit the one you got by id i.e. CP ? e.g.
edited_page = CP
edited_page.title = title
edited_page.content = content
edited_page.type = type
edited_page.reference = reference
edited_page.template = template
edited_page.put()

Categories

Resources