I am trying to update a listfield of embedded documents in mongoengine. I have gone through almost all the related questions but somehow my code just won't work. I know there is something small that I'm missing but I can't figure it out.
Here is my code :
Documents:
class Address(EmbeddedDocument):
line1 = StringField(required=True, max_length=63)
line2 = StringField(max_length=127)
pin = StringField(max_length=6, min_length=6)
class Store(EmbeddedDocument):
code = StringField(max_length=50, required=True)
store_name = StringField(max_length=255, required=True)
address = EmbeddedDocumentField(Address)
class Vendor(Document):
name = StringField(max_length=255, required=True)
stores = ListField(EmbeddedDocumentField(Store))
View:
def stores(request, *args, **kwargs):
.......
elif request.method == 'POST':
if request.is_ajax():
if request.POST.get('oper') == 'edit':
post_dict = request.POST
# updated_vendor = Vendor.objects(pk=vendor_pk, stores__$__)
vendor.update_store(vendor_pk, post_dict)
return get_json_response({'msg': 'Store details updated successfully!!'})
else:
....
def update_store(self, vendor_pk, post_dict):
print post_dict
store = [attr for attr in self.stores if attr.code == post_dict.get('code') and attr.store_name == post_dict.get('store_name')]
vendor = self
new_address = Address(line1=post_dict.get('line1'), line2=post_dict.get('line2'),
city=post_dict.get('city'), state=post_dict.get('state'),
country=post_dict.get('country'))
if post_dict.get('pin') != 'None':
new_address.pin = post_dict.get('pin')
print "address new", new_address.line2, new_address.pin
new_store = Store(code=post_dict.get('code'), store_name=post_dict.get('store_name'), address=new_address)
print "new store", new_store.address.line2, new_store.address.pin
if store:
index = vendor.stores.index(store[0])
updated = Vendor.objects(pk=vendor_pk, stores__code=post_dict.get('code'), stores__name=post_dict.get('store_name')).update_one(set__stores__index=new_store)
print "updated", updated
#print index,vendor.stores[index].address.city
# del vendor.stores[index]
# vendor.stores.append(new_store)
# vendor.stores[index].code = post_dict.get('code')
# vendor.stores[index].store_name = post_dict.get('store_name')
# vendor.stores[index].address.line1 = post_dict.get('line1')
# vendor.stores[index].address.line2 = post_dict.get('line2')
# if post_dict['pin'] != 'None':
# vendor.stores[index].address.pin = post_dict.get('pin')
# vendor.save()
These are my print statements' output :
<QueryDict: {u'oper': [u'edit'], u'code': [u'BSK'], u'pin': [u'1'], u'line2': [u'near huda city center'], u'line1': [u'Shushant Lok'], u'store_name': [u'Baskin'], u'id': [u'2']}>
address new near huda city center 1
new store near huda city center 1
updated 0
My update_store method just won't work. Please Help.
Ok So I got my code to work now.
I modified my update_store method to this and it worked.
def update_store(self, post_dict):
vendor = self
new_address = Address(line1=post_dict.get('line1'), line2=post_dict.get('line2'))
if post_dict.get('pin') != 'None':
new_address.pin = post_dict.get('pin')
new_store = Store(code=post_dict.get('code'), store_name=post_dict.get('store_name'), address=new_address)
index = int(post_dict.get('id')) -1
stores = vendor.get_active_stores()
stores[index].is_active = False
vendor.stores.append(new_store)
vendor.save()
Related
This method to get the product price from the PO, and it works well if the PO have only one record otherwise I am getting this error.
raise ValueError("Expected singleton: %s" % self)
This is the method
#api.multi
def create_refund_invoice(self):
inv_obj = self.env['account.invoice']
for pick in self.filtered(lambda x:x.return_type):
type = 'in_refund' if pick.return_type == 'purchase' else 'out_refund'
inv_lines = {'type':type, 'partner_id':pick.partner_id.id, 'invoice_line_ids':[]}
account = pick.return_type == 'sale' and pick.partner_id.property_account_receivable_id.id or pick.partner_id.property_account_payable_id.id
inv_lines['account_id'] = account
inv_lines['origin'] = pick.name
inv_lines['name'] = pick.origin
for line in pick.move_lines:
name = line.product_id.partner_ref
for rec in self:
rec.order_id = line.env['purchase.order'].search([('name', '=', line.origin)]).order_line
rec.price = rec.order_id.price_unit
inv_lines['invoice_line_ids'] += [(0, None, {
'product_id':line.product_id.id,
'name':name,
'quantity':line.quantity_done,
'price_unit': rec.price,
'account_id':line.product_id.product_tmpl_id.get_product_accounts()['income'].id})]
if inv_lines['invoice_line_ids']:
inv_id = inv_obj.create(inv_lines)
pick.invoice_id = inv_id.id
It is necessary for odoo that when you are getting more than one record then you can not access it's field values directly.
In your code you are trying to get purchase_order_line of purchase_order It may possible that many lines are available in a single order.
def create_refund_invoice(self):
purchase_order_obj = self.env['purchase.order']
inv_obj = self.env['account.invoice']
for pick in self.filtered(lambda x:x.return_type):
type = 'in_refund' if pick.return_type == 'purchase' else 'out_refund'
inv_lines = {'type':type, 'partner_id':pick.partner_id.id, 'invoice_line_ids':[]}
account = pick.return_type == 'sale' and pick.partner_id.property_account_receivable_id.id or pick.partner_id.property_account_payable_id.id
inv_lines['account_id'] = account
inv_lines['origin'] = pick.name
inv_lines['name'] = pick.origin
for line in pick.move_lines:
name = line.product_id.partner_ref
for rec in self:
order_lines = purchase_order_obj.search([('name', '=', line.origin)]).order_line
for pol in order_lines:
price = pol.order_id.price_unit
inv_lines['invoice_line_ids'] += [(0, None, {
'product_id':line.product_id.id,
'name':name,
'quantity':line.quantity_done,
'price_unit': price,
'account_id':line.product_id.product_tmpl_id.get_product_accounts()['income'].id})
]
if inv_lines['invoice_line_ids']:
inv_id = inv_obj.create(inv_lines)
pick.invoice_id = inv_id.id
I have updated code test above code and update it as per your requirement.
I create new record with the method named create() in local database with data pulled away from remote database.As we all know,there are four normal fields in Odoo such as create_date,write_date,create_uid,write_uid.I want these data to be in a remote database,but when I use method named create() to create the record,these data are the data at the time of local creation and not the remote data.
For example,in remote database,the creat_date is '2019-10-11',I can't change the value that is finally written to the local database even if I pass the value of the remote database into the dictionary.Finally,the value of field named create_date is '2019-12-03' rather than '2019-10-11'.The '2019-12-03' is the date now.The situation is similar for other fields such as write_date,create_uid,write_uid.
Please help me,thanks to everyone who thought about this question.
Following is my code.
The Class Model
class ReportRentalIncomeFromProperty(models.Model):
_name = 'report.rental.income.from.property'
_description = 'The report about the income from property rental'
_order = 'product_id, start_date'
# create_date = fields.Datetime('Created on')
create_uid = fields.Char('Created by')
# write_date = fields.Datetime('Last Modified on')
write_uid = fields.Char('Last Contributor')
product_id = fields.Many2one('product.product', 'Property House')
area_id = fields.Many2one('res.country.area', 'City')
district_id = fields.Many2one('res.country.district', 'District')
town_id = fields.Many2one('res.country.town', 'Town')
road_name = fields.Char('Road')
start_date = fields.Date('Start Date')
end_date = fields.Date('End Date')
should_pay = fields.Float('Should Pay')
real_pay = fields.Float('Real Pay')
balance_pay = fields.Float('Balance Pay')
rental_compliance_rate = fields.Float('Rental Compliance Rate(%)', group_operator="avg")
company_id = fields.Many2one('res.company', string='Company')
parent_company_id = fields.Many2one('res.company', related='company_id.parent_id', store=True,
string='Parent Company')
actual_business = fields.Many2many(
'rh.commercial.activities',
'house_rental_rent_income_business_db',
'actual_business_id',
'commercial_activities_id',
string='Actual business')
The function to pull away remote data to create new record in local database.
#api.multi
def synchronization_contract_performance_rate(self):
self.env['report.rental.income.from.property'].search([]).unlink()
product_dict = {}
A_product = self.env['product.product'].search([])
for a in A_product:
product_dict[a.name] = a.id
activities_dict = {}
D_activities = self.env['rh.commercial.activities'].search([])
for d in D_activities:
activities_dict[d.name] = d.id
address_dict = {}
i = 0
address_model_list = ['res.country.area', 'res.country.district', 'res.country.town']
address_field_list = ['area_id', 'district_id', 'town_id']
for addr in address_model_list:
C_address = self.env[addr].search([])
addr_dict = {}
for c in C_address:
addr_dict[c.name] = c.id
address_dict[i] = addr_dict
i += 1
record_list_1 = self.company_recursive_func()
for list_1 in record_list_1:
database = list_1[0]
link_url = list_1[1]
if link_url.startswith('http://'):
_uri = link_url.replace('http://', '')
my_odoo = odoorpc.ODOO(_uri, port=48080)
if link_url.startswith('https://'):
_uri = link_url.replace('https://', '')
my_odoo = odoorpc.ODOO(_uri, port=443, protocol='jsonrpc+ssl')
username = list_1[2]
password = list_1[3]
my_odoo.login(database, username, password)
company_id = list_1[4]
company_code = list_1[5]
product_actual_business_dict = {}
A_product_actual_business_ids = my_odoo.env['product.product'].search([])
A_product_actual_business = my_odoo.execute('product.product', 'read', A_product_actual_business_ids,
['actual_business'])
for a in A_product_actual_business:
name_list = []
for b in my_odoo.execute('rh.commercial.activities', 'read', a.get('actual_business'), ['name']):
name_list.append(b.get('name'))
product_actual_business_dict[a.get('id')] = name_list
remote_ids = my_odoo.env['report.rental.income.from.property'].search([])
remote_data_dict = my_odoo.execute('report.rental.income.from.property', 'read', remote_ids, ['product_id',
'start_date',
'create_date',
'create_uid',
'write_date',
'write_uid',
'end_date',
'should_pay',
'balance_pay',
'real_pay',
'rental_compliance_rate',
'area_id',
'road_name',
'district_id',
'town_id'])
for data in remote_data_dict:
remote_product_name = data.get('product_id')[1]
product_id = product_dict.get(remote_product_name + '(' + company_code + ')',
None)
if product_id:
i = 0
address_id_list = []
for address_field in address_field_list:
if data.get(address_field):
remote_address_name = data.get(address_field)[1]
local_address_id = address_dict[i].get(remote_address_name, None)
address_id_list.append(local_address_id)
else:
address_id_list.append(None)
i += 1
ids_list = []
find_names = product_actual_business_dict.get(data.get('product_id')[0])
for find_name in find_names:
id = activities_dict.get(find_name, None)
if id:
ids_list.append(id)
value = {
'product_id': product_id,
'area_id': address_id_list[0],
'district_id': address_id_list[1],
'town_id': address_id_list[2],
'road_name': data['road_name'],
'start_date': data['start_date'],
'end_date': data['end_date'],
'should_pay': data['should_pay'],
'real_pay': data['real_pay'],
'create_date': data['create_date'],
'create_uid': data['create_uid'][1],
'write_date': data['write_date'],
'write_uid': data['write_uid'][1],
'balance_pay':data['balance_pay'],
'rental_compliance_rate': data['rental_compliance_rate'],
'company_id': company_id,
'actual_business': [(6, 0, ids_list)]
}
self.env['report.rental.income.from.property'].create(value)
my_odoo.logout()
You can change standart odoo fields after you create your record with sql query
property_id = self.env['report.rental.income.from.property'].create(value)
self.env.cr.execute("UPDATE report_rental_income_from_property SET create_date='%s', create_uid=%s, write_date='%s', write_uid=%s WHERE id=%s" %
(value['create_date'], value['create_uid'], value['write_date'], value['write_uid'], property_id))
I have a method that tells the times that a worker makes a sale, but it does not work because it only marks me that he has made 1 but has actually done 5. Next I leave an image and the code used to guide me.
**class Worker (models.Model):**
_name = 'project_rc.worker'
sales_counter = fields.Integer (string = "Sales made", compute = "get_sales_made")
document_ids = fields.One2many (comodel_name = 'project_rc.document',
inverse_name = 'worker_id', string = 'Invoice')
def get_sales_made (self):
count = self.env ['project_rc.type_movement']. search_count ([('type_movement', '=', 'sale')])
self.counter_sale = count
**class Document (models.Model):**
type_movement_id = fields.Many2one (comodel_name = 'project_rc.type_movement', string = "Movement type")
worker_id = fields.Many2one (asdel_name = 'project_rc.worker', string = "Worker")
**class Type_Movement (models.Model):**
type_movement = fields.Selection ([('purchase', 'Purchase'), ('sale', 'Sale'), ('merma', 'Merma')], string = "Movement type")
document_ids = fields.One2many (comodel_name = 'project_rc.document', inverse_name = 'type_movimiento_id', string = 'Document')
Sample picture: https://ibb.co/vs0dw5K
The problem came from your function get_sales_made
class Worker(models.Model):
_name = 'project_rc.worker'
sales_counter = fields.Integer(string="Sales made", compute="get_sales_made")
document_ids = fields.One2many('project_rc.document', 'worker_id', string='Invoice')
#api.depends('document_ids')
def get_sales_made(self):
for rec in self:
document = rec.document_ids.filtered(lambda r: r.type_movement_id and r.type_movement_id.type_movement == 'sale')
rec.sales_counter = len(document)
class Document(models.Model):
_name = 'project_rc.document'
type_movement_id = fields.Many2one('project_rc.type_movement', string="Movement type")
worker_id = fields.Many2one('project_rc.worker', string="Worker")
class Type_Movement(models.Model):
_name = 'project_rc.type_movement'
type_movement = fields.Selection([('purchase', 'Purchase'), ('sale', 'Sale'), ('merma', 'Merma')], string="Movement type")
document_ids = fields.One2many('project_rc.document', 'type_movement_id', string='Document')
You are searching in the wrong table it should be project_rc.document
self.env['project_rc.document'].search_count([('type_movement_id.type_movement', '=', 'sale')
('worker_id', '=', rec.id)
])
Or you can simply filter document_ids to count sales.
I have a question for some of you who are familiar with the Revit API and python:
I’ve been using the spring nodes package in dynamo to create a rather large series of freeform objects each in their own family. The way that the FamilyInstance.ByGeometry works, it takes a list of solids and creates a family instance for each using a template family file. The result is quite good. (spring nodes can be found here: https://github.com/dimven/SpringNodes)
However, the drawback is that that now I have roughly 200 separate instances, so to make changes to each is rather painful. I thought at first it would be possible to use dynamo to create a new subcategory and set the solid inside each family instance to this new subcategory. Unfortunately, I realized this is not possible since dynamo cannot be open in two different Revit environments simultaneously (the project I am working in and each instance of the family). This leads me to look to see if I can do this using python.
I have used python in rhino and can get along pretty well, I am still learning the Revit API however. But basically my idea would be to:
1. select a series of family instances in the Revit project environment
2. loop through each instance
3. save it to a specified location
4. create a new subcategory in each family instances (the subcategory would the same for all the selected family instances)
5. select the solid in each in instance
6. set the solid to this newly created subcategory
7. close the family instance and save
My question for you is does this sound like it is achievable based on your knowledge of the Revit API?
Many thanks for your time and advice.
UPDATE:
I've found a section in the revit api that describes what i'm looking to do: http://help.autodesk.com/view/RVT/2015/ENU/?guid=GUID-FBF9B994-ADCB-4679-B50B-2E9A1E09AA48
I've made a first pass at inserting this into the python code of the dynamo node. The rest of the code works fine except for the new section im adding (see below). Please excuse the variables, I am simply keeping with logic of the original author of the code i am hacking:
(Note: the variables come in are in arrays)
#set subcategory
try:
#create new sucategory
fam_subcat = famdoc.Settings.Categories.NewSubcategory(fam_cat, get_Item(subcat1.Name))
#assign the mataterial(fam_mat.Id) to the subcategory
fam_subcat.Material = famdoc.GetElement(fam_mat.Id)
#assign the subcategory to the element (s2)
s2.Subcategory = fam_subcat
except: pass
Any help or advice with this section of code would be much appreciated.
UPDATE:
See full code below for context of the section in question:
#Copyright(c) 2015, Dimitar Venkov
# #5devene, dimitar.ven#gmail.com
import clr
import System
from System.Collections.Generic import *
pf_path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFilesX86)
import sys
sys.path.append("%s\IronPython 2.7\Lib" %pf_path)
import traceback
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference("RevitServices")
import RevitServices
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager
doc = DocumentManager.Instance.CurrentDBDocument
app = DocumentManager.Instance.CurrentUIApplication.Application
clr.AddReference("RevitAPI")
from Autodesk.Revit.DB import *
from Autodesk.Revit.DB.Structure import StructuralType
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Elements)
clr.ImportExtensions(Revit.GeometryConversion)
def tolist(obj1):
if hasattr(obj1,"__iter__"): return obj1
else: return [obj1]
def output1(l1):
if len(l1) == 1: return l1[0]
else: return l1
def PadLists(lists):
len1 = max([len(l) for l in lists])
for i in xrange(len(lists)):
if len(lists[i]) == len1:
continue
else:
len2 = len1 - len(lists[i])
for j in xrange(len2):
lists[i].append(lists[i][-1])
return lists
class FamOpt1(IFamilyLoadOptions):
def __init__(self):
pass
def OnFamilyFound(self,familyInUse, overwriteParameterValues):
return True
def OnSharedFamilyFound(self,familyInUse, source, overwriteParameterValues):
return True
geom = tolist(IN[0])
fam_path = IN[1]
names = tolist(IN[2])
category = tolist(IN[3])
material = tolist(IN[4])
isVoid = tolist(IN[5])
subcategory = tolist(IN[6])
isRvt2014 = False
if app.VersionName == "Autodesk Revit 2014": isRvt2014 = True
units = doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits
factor = UnitUtils.ConvertToInternalUnits(1,units)
acceptable_views = ["ThreeD", "FloorPlan", "EngineeringPlan", "CeilingPlan", "Elevation", "Section"]
origin = XYZ(0,0,0)
str_typ = StructuralType.NonStructural
def NewForm_background(s1, name1, cat1, isVoid1, mat1, subcat1):
t1 = TransactionManager.Instance
TransactionManager.ForceCloseTransaction(t1)
famdoc = doc.Application.NewFamilyDocument(fam_path)
message = None
temp_path = System.IO.Path.GetTempPath()
sat_path = "%s%s.sat" % (temp_path, name1)
try:
if factor != 1:
s1 = s1.Scale(factor)
sat1 = Geometry.ExportToSAT(s1, sat_path)
satOpt = SATImportOptions()
satOpt.Placement = ImportPlacement.Origin
satOpt.Unit = ImportUnit.Foot
view_fec = FilteredElementCollector(famdoc).OfClass(View)
view1 = None
for v in view_fec:
if str(v.ViewType) in acceptable_views:
view1 = v
break
t1.EnsureInTransaction(famdoc)
satId = famdoc.Import(sat1, satOpt, view1)
opt1 = Options()
opt1.ComputeReferences = True
el1 = famdoc.GetElement(satId)
geom1 = el1.get_Geometry(opt1)
enum = geom1.GetEnumerator()
enum.MoveNext()
geom2 = enum.Current.GetInstanceGeometry()
enum2 = geom2.GetEnumerator()
enum2.MoveNext()
s1 = enum2.Current
famdoc.Delete(satId)
TransactionManager.ForceCloseTransaction(t1)
System.IO.File.Delete(sat_path)
except:
message = traceback.format_exc()
pass
if message == None:
try:
save_path = "%s%s.rfa" % (temp_path, name1)
SaveAsOpt = SaveAsOptions()
SaveAsOpt.OverwriteExistingFile = True
t1.EnsureInTransaction(famdoc)
#set the category
try:
fam_cat = famdoc.Settings.Categories.get_Item(cat1.Name)
famdoc.OwnerFamily.FamilyCategory = fam_cat
except: pass
s2 = FreeFormElement.Create(famdoc,s1)
if isVoid1:
void_par = s2.get_Parameter("Solid/Void")
void_par.Set(1)
void_par2 = famdoc.OwnerFamily.get_Parameter("Cut with Voids When Loaded")
void_par2.Set(1)
else: #voids do not have a material value
try:
mat_fec = FilteredElementCollector(famdoc).OfClass(Material)
for m in mat_fec:
if m.Name == mat1:
fam_mat = m
break
mat_par = s2.get_Parameter("Material")
mat_par.Set(fam_mat.Id)
except: pass
#set subcategory
try:
#create new sucategory
fam_subcat = document.Settings.Categories.NewSubcategory(document.OwnerFamily.FamilyCategory, get_Item(subcat1.Name))
#assign the mataterial(fam_mat.Id) to the subcategory
fam_subcat.Material = famdoc.GetElement(fam_mat.Id)
#assign the subcategory to the element (s2)
s2.Subcategory = fam_subcat
except: pass
TransactionManager.ForceCloseTransaction(t1)
famdoc.SaveAs(save_path, SaveAsOpt)
family1 = famdoc.LoadFamily(doc, FamOpt1())
famdoc.Close(False)
System.IO.File.Delete(save_path)
symbols = family1.Symbols.GetEnumerator()
symbols.MoveNext()
symbol1 = symbols.Current
t1.EnsureInTransaction(doc)
if not symbol1.IsActive: symbol1.Activate()
inst1 = doc.Create.NewFamilyInstance(origin, symbol1, str_typ)
TransactionManager.ForceCloseTransaction(t1)
return inst1.ToDSType(False), family1.ToDSType(False)
except:
message = traceback.format_exc()
return message
else:
return message
def NewForm_background_R16(s1, name1, cat1, isVoid1, mat1, subcat1):
t1 = TransactionManager.Instance
TransactionManager.ForceCloseTransaction(t1)
famdoc = doc.Application.NewFamilyDocument(fam_path)
message = None
temp_path = System.IO.Path.GetTempPath()
sat_path = "%s%s.sat" % (temp_path, name1)
try:
if factor != 1:
s1 = s1.Scale(factor)
sat1 = Geometry.ExportToSAT(s1, sat_path)
satOpt = SATImportOptions()
satOpt.Placement = ImportPlacement.Origin
satOpt.Unit = ImportUnit.Foot
view_fec = FilteredElementCollector(famdoc).OfClass(View)
view1 = None
for v in view_fec:
if str(v.ViewType) in acceptable_views:
view1 = v
break
t1.EnsureInTransaction(famdoc)
satId = famdoc.Import(sat1, satOpt, view1)
opt1 = Options()
opt1.ComputeReferences = True
el1 = famdoc.GetElement(satId)
geom1 = el1.get_Geometry(opt1)
enum = geom1.GetEnumerator()
enum.MoveNext()
geom2 = enum.Current.GetInstanceGeometry()
enum2 = geom2.GetEnumerator()
enum2.MoveNext()
s1 = enum2.Current
famdoc.Delete(satId)
TransactionManager.ForceCloseTransaction(t1)
System.IO.File.Delete(sat_path)
except:
message = traceback.format_exc()
pass
if message == None:
try:
save_path = "%s%s.rfa" % (temp_path, name1)
SaveAsOpt = SaveAsOptions()
SaveAsOpt.OverwriteExistingFile = True
t1.EnsureInTransaction(famdoc)
#set the category
try:
fam_cat = famdoc.Settings.Categories.get_Item(cat1.Name)
famdoc.OwnerFamily.FamilyCategory = fam_cat
except: pass
s2 = FreeFormElement.Create(famdoc,s1)
if isVoid1:
void_par = s2.LookupParameter("Solid/Void")
void_par.Set(1)
void_par2 = famdoc.OwnerFamily.LookupParameter("Cut with Voids When Loaded")
void_par2.Set(1)
else: #voids do not have a material value
try:
mat_fec = FilteredElementCollector(famdoc).OfClass(Material)
for m in mat_fec:
if m.Name == mat1:
fam_mat = m
break
mat_par = s2.LookupParameter("Material")
mat_par.Set(fam_mat.Id)
except: pass
#apply same subcategory code as before
#set subcategory
try:
#create new sucategory
fam_subcat = famdoc.Settings.Categories.NewSubcategory(fam_cat, get_Item(subcat1.Name))
#assign the mataterial(fam_mat.Id) to the subcategory
fam_subcat.Material = famdoc.GetElement(fam_mat.Id)
#assign the subcategory to the element (s2)
s2.Subcategory = fam_subcat
except: pass
TransactionManager.ForceCloseTransaction(t1)
famdoc.SaveAs(save_path, SaveAsOpt)
family1 = famdoc.LoadFamily(doc, FamOpt1())
famdoc.Close(False)
System.IO.File.Delete(save_path)
symbols = family1.GetFamilySymbolIds().GetEnumerator()
symbols.MoveNext()
symbol1 = doc.GetElement(symbols.Current)
t1.EnsureInTransaction(doc)
if not symbol1.IsActive: symbol1.Activate()
inst1 = doc.Create.NewFamilyInstance(origin, symbol1, str_typ)
TransactionManager.ForceCloseTransaction(t1)
return inst1.ToDSType(False), family1.ToDSType(False)
except:
message = traceback.format_exc()
return message
else:
return message
if len(geom) == len(names) == len(category) == len(isVoid) == len(material) == len(subcategory):
if isRvt2014:
OUT = output1(map(NewForm_background, geom, names, category, isVoid, material, subcategory))
else:
OUT = output1(map(NewForm_background_R16, geom, names, category, isVoid, material, subcategory))
elif len(geom) == len(names):
padded = PadLists((geom, category, isVoid, material, subcategory))
p_category = padded[1]
p_isVoid = padded[2]
p_material = padded[3]
p_subcategory = padded [4]
if isRvt2014:
OUT = output1(map(NewForm_background, geom, names, p_category, p_isVoid, p_material, p_subcategory))
else:
OUT = output1(map(NewForm_background_R16, geom, names, p_category, p_isVoid, p_material, subcategory))
else: OUT = "Make sure that each geometry\nobject has a unique family name."
Update:
Was able to get it working:
try:
#create new sucategory
fam_subcat = famdoc.Settings.Categories.NewSubcategory(famdoc.OwnerFamily.FamilyCategory, subcat1)
#assign the mataterial(fam_mat.Id) to the subcategory
#fam_subcat.Material = famdoc.GetElement(fam_mat.Id)
#assign the subcategory to the element (s2)
s2.Subcategory = fam_subcat
except: pass
As I answered on your initial query per email, what you are aiming for sounds perfectly feasible to me in the Revit API. Congratulations on getting as far as you have. Looking at the link to the Revit API help file and developer guide that you cite above, it seems that the code has to be executed in the family document while defining the family. The context in which you are trying to execute it is not clear. Have you used EditFamily to open the family definition document? What context are you executing in?
This line of code:
geted_nickname = user.nickname()
Of this Handler:
class MainHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user == None:
self.redirect(users.create_login_url(self.request.uri))
geted_nickname = user.nickname()
Is producing this error:
File "C:\Users\Py\Desktop\Apps\contract\main.py", line 99, in get
geted_nickname = user.nickname()
AttributeError: 'NoneType' object has no attribute 'nickname'
Since user is a NoneType object, the program should execute the if block self.redirect(users.create_login_url(self.request.uri)) , but this isn't happening. Why? How to fix that?
Thanks for any help!
Here the entire code:
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
import os
import webapp2
import jinja2
jinja_environment = jinja2.Environment(autoescape=True,
loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))
import re
from google.appengine.ext import db
USER_RE = re.compile(r"^[a-zA-Z0-9_ -]{3,20}$")
def valid_person(person):
return USER_RE.match(person)
PASS_RE = re.compile(r"^.{3,20}$")
def valid_SSN(SSN):
return PASS_RE.match(SSN)
EMAIL_RE = re.compile(r"^[\S]+#[\S]+\.[\S]+$")
def valid_email(email):
return EMAIL_RE.match(email)
clauses = {u'Software development agreement':"Don't be evil", 'Car Rental Contract':"non-skid the tires", 'House Rental Contract':"Don't break stuff"}
import time
import datetime
def dateToday():
today = datetime.datetime.today()
todayDay = str(today.day)
todayMonth = str(today.month)
monthExt = {'1':' January ', '2':'February', '3':' March ', '4':'April', '5':'May', '6':'June', '7':' July ', '8':'August', '9':'September', '10':'October', '11':'November ', '12':'December'}
todayYear = str(today.year)
return(todayDay + ' of ' + monthExt[todayMonth] + ' of ' + todayYear)
class Person(db.Model):
person_name = db.StringProperty(required = True)
nacionality = db.StringProperty(required = True)
marital_status = db.StringProperty(required = True)
profession = db.StringProperty(required = True)
SSN = db.IntegerProperty(required = True)
driver_license = db.IntegerProperty(required = True)
address = db.address = db.PostalAddressProperty(required = True)
class Contract(db.Model):
book_number = db.IntegerProperty(required = True)
initial_page = db.IntegerProperty(required = True)
final_page = db.IntegerProperty(required = True)
contract_type = db.StringProperty(required = True)
date = db.DateProperty (required = True, auto_now = True, auto_now_add = True)
class RegisteredUser(db.Model):
user_name = db.UserProperty()
user_nickname = db.StringProperty()
name = db.StringProperty()
user_position = db.StringProperty()
org_name = db.StringProperty()
org_address = db.StringProperty()
org_city = db.StringProperty()
org_state = db.StringProperty()
class ContractingParty(db.Model):
person = db.ReferenceProperty(Person, required=True, collection_name="party_to_contracts")
contract = db.ReferenceProperty(Contract, required=True)
condition = db.StringProperty(required = True, choices=set(["active position", "passive position", "witness"]))
class MainHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user == None:
self.redirect(users.create_login_url(self.request.uri))
geted_nickname = user.nickname()
registeredUser = db.GqlQuery("SELECT * FROM RegisteredUser WHERE user_nickname =:nickname", nickname = geted_nickname).get()
if registeredUser is None:
self.redirect('/register?user_nickname=%s' % (geted_nickname))
contract = db.GqlQuery("SELECT * FROM Contract ORDER BY date DESC").get()
if contract == None:
numBook = 1
numInitialPage = 1
numFinalPage = 1
else:
numBook = contract.book_number
numInitialPage = contract.final_page +1
numFinalPage = numInitialPage
template_values = {"numBook": numBook,
"numInitialPage": numInitialPage,
"numFinalPage": numFinalPage}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
def post(self):
choosed_contract_type = self.request.get("contract_type")
numBook = self.request.get("numBook")
numInitialPage = self.request.get("numInitialPage")
numFinalPage = self.request.get("numFinalPage")
person_name = self.request.get("person_name")
user_nacionality = self.request.get('nacionality')
user_profession = self.request.get('profession')
user_marital_status = self.request.get('marital_status')
user_driver_license = self.request.get('driver_license')
driver_license_error = ''
user_SSN = self.request.get('SSN')
SSN_error = ""
address = self.request.get('address')
person_name2 = self.request.get("person_name2")
user_nacionality2 = self.request.get('nacionality2')
user_profession2 = self.request.get('profession2')
user_marital_status2 = self.request.get('marital_status2')
user_driver_license2 = self.request.get('driver_license2')
user_SSN2 = self.request.get('SSN2')
SSN_error2 = ""
address2 = self.request.get('address2')
bsubmit = self.request.get('bsubmit')
if (bsubmit == 'Submit Contract') and (person_name and valid_person(person_name)) and (user_SSN and valid_SSN(user_SSN)):
contract_record = Contract(book_number = int(numBook),
initial_page = int(numInitialPage),
final_page = int(numFinalPage),
contract_type = choosed_contract_type)
contract_record.put()
contract_id = contract_record.key().id()
person_record = Person(person_name = person_name,
nacionality = user_nacionality,
profession = user_profession,
marital_status = user_marital_status,
driver_license = int(user_driver_license),
SSN = int(user_SSN),
address = address)
person_record.put()
person_id = person_record.key().id()
person_record2 = Person(person_name = person_name2,
nacionality = user_nacionality2,
profession = user_profession2,
marital_status = user_marital_status2,
driver_license = int(user_driver_license2),
SSN = int(user_SSN2),
address = address2)
person_record2.put()
person_id2 = person_record2.key().id()
self.redirect('/your_contract?contract_id=%s&person_id=%s&person_id2=%s' % (contract_id, person_id, person_id2))
else:
if not person_name or not valid_person(person_name):
person_name_error = "Oh no!!! this person name isn't valid!"
if not user_SSN or not valid_SSN(user_SSN):
SSN_error = "Oh no!!! SSN isn't valid!"
template_values = {"person_name": person_name,
"nacionality": user_nacionality,
"marital_status": user_marital_status,
"profession": user_profession,
"SSN": user_SSN,
"driver_license": user_driver_license,
## "email": user_email,
"person_name_error": person_name_error,
"SSN_error": SSN_error,
"driver_license_error": user_driver_license,
"address": address,
"person_name2":person_name2,
"nacionality2":user_nacionality2,
"marital_status2":user_marital_status2,
"profession2":user_profession2,
"driver_license2":user_driver_license2,
"SSN2":user_SSN2,
"address2":user_address2,
"contract_type":choosed_contract_type,
"numBook":geted_numBook,
"numInitialPage":geted_numInitialPage,
"numFinalPage":geted_numInitialPage,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(template.render(template_values))
class your_contractHandler(webapp2.RequestHandler):
def get(self):
contract_id = self.request.get('contract_id')
contract = Contract.get_by_id(int(contract_id))
geted_contract_type = contract.contract_type
geted_clauses = clauses[geted_contract_type]
geted_numBook = contract.book_number
geted_numInitialPage = contract.initial_page
geted_numFinalPage = contract.final_page
geted_dateToday = dateToday()
user = users.get_current_user()
geted_nickname = user.nickname()
registered_user = db.GqlQuery("SELECT * FROM RegisteredUser WHERE user_nickname =:nickname", nickname = geted_nickname).get()
geted_autor_ato = registered_user.user_name
user_position = registered_user.user_position
org_name = registered_user.org_name
org_city = registered_user.org_city
org_state = registered_user.org_state
person_id = self.request.get('person_id')
person = Person.get_by_id(int(person_id))
geted_person_name = person.person_name
geted_user_nacionality = person.nacionality
geted_user_profession = person.profession
geted_user_marital_status = person.marital_status
geted_user_driver_license = person.driver_license
geted_user_SSN = person.SSN
geted_user_address = person.address
person_id2 = self.request.get('person_id2')
person2 = Person.get_by_id(int(person_id2))
geted_person_name2 = person2.person_name
geted_user_nacionality2 = person2.nacionality
geted_user_profession2 = person2.profession
geted_user_marital_status2 = person2.marital_status
geted_user_driver_license2 = person2.driver_license
geted_user_SSN2 = person2.SSN
geted_user_address2 = person2.address
your_contract = jinja_environment.get_template('your_contract.html')
your_contract_values = {"autor_ato":geted_autor_ato,
"user_position":user_position,
"org_name":org_name,
"org_city":org_city,
"org_state":org_state,
"contract_type":geted_contract_type,
"clauses":geted_clauses,
"dateContract":geted_dateToday,
"numBook":geted_numBook,
"numInitialPage":geted_numInitialPage,
"numFinalPage":geted_numInitialPage,
"person_name":geted_person_name,
"nacionality":geted_user_nacionality,
"marital_status":geted_user_marital_status,
"profession": geted_user_profession,
"driver_license":geted_user_driver_license,
"SSN":geted_user_SSN,
"address":geted_user_address,
"person_name2":geted_person_name2,
"nacionality2":geted_user_nacionality2,
"marital_status2":geted_user_marital_status2,
"profession2": geted_user_profession2,
"driver_license2":geted_user_driver_license2,
"SSN2":geted_user_SSN2,
"address2":geted_user_address2,
}
template = jinja_environment.get_template('index.html')
self.response.out.write(your_contract.render(your_contract_values))
class RegisterHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if not user:
self.redirect(users.create_login_url(self.request.uri))
nickname = user.nickname()
template_values = {"user_nickname": nickname}
template = jinja_environment.get_template('register.html')
self.response.out.write(template.render(template_values))
def post(self):
user = users.get_current_user()
geted_user_nickname = user.nickname()
geted_user_name = self.request.get("user_name")
geted_user_position = self.request.get('position')
geted_org_name = self.request.get('org_name')
geted_org_address = self.request.get('org_adress')
geted_address = self.request.get('address')
geted_city = self.request.get('city')
registered_user = RegisteredUser(user = user,
user_name = geted_user_name,
user_nickname = geted_user_nickname,
position = geted_user_position,
org_name = geted_org_name,
org_address = geted_org_address,
city = geted_city,
)
registered_user.put()
## registered_user_id = registered_user.key().id()
self.redirect('/')
app = webapp2.WSGIApplication([('/', MainHandler), ('/your_contract', your_contractHandler), ('/register', RegisterHandler)],
debug=True)
According to the docs calling redirect does not stop code execution unless abort is set to True. It suggests returning the result of the redirect, e.g.:
return redirect('/some-path')
In your case, your method keeps executing, and user, which is None, is looking up an attribute that doesn't exist.