Create Views if they do not exist

Hi,
I’m trying to work up a python code to create 2 views if they don’t exist in the project.
But am struggling with it, any help would be appreciated.

import clr
clr.AddReference('RevitAPI')
import Autodesk
from Autodesk.Revit.DB import*

clr.AddReference('RevitServices')
from RevitServices.Persistence import DocumentManager
from RevitServices.Transactions import TransactionManager

# The inputs to this node will be stored as a list in the IN variables.
ExistViews = UnwrapElement(IN[0])

# Place your code below this line
output = []
doc = DocumentManager.Instance.CurrentDBDocument
lvls = FilteredElementCollector(doc).OfClass(Level).ToElements() #Collect all levels
#uidoc = DocumentManager.Instance.CurrentUIApplication.ActiveDocument

def _Create3DView(viewname):
	#Get all view types
	viewTypes = FilteredElementCollector(doc).ofClass(ViewFamilyType)
	
	#Get ID of 3D view type
	for i in viewTypes:
		if i.ViewFamily == ViewFamily.ThreeDimensional:
			view3DTypeId = i.Id
			break
			
	TransactionManager.Instance.EnsureInTransaction(doc)
			
	NewView = View3D.CreateIsometric(doc, view3DTypeId)
	NewView.Name = viewname #"3D Dwfx Export"
#	TransActionManager.Instance.TransactionTaskDone()
	return NewView

TransactionManager.Instance.EnsureInTransaction(doc)

for View in ExistViews:
	
	if not View == "DWFx Plan View":
		viewTypes = FilteredElementCollector(doc).OfClass(ViewFamilyType).ToElements()

#		Get ID of 3D view type
		for ix in viewTypes:
			if ix.ViewFamily == ViewFamily.FloorPlan:
				viewTypeId = ix.Id
			break
		
		NewView = ViewPlan.Create(doc, viewtypeId, lvls)
		NewView.Name = "DWFx Plan View"
			
	if not View == "3D Dwfx Export":
		_Create3DView("3D Dwfx Export")

output.append(NewView.ToDSType(True))
TransActionManager.Instance.TransactionTaskDone()
# Assign your output to the OUT variable.
OUT = output

Why don’t you simply create the views, inside a try except block?
If a view both same name exists, it will throw an error, so no view will created

Hello @EddieSaez

there are quite a few errors in your code.

it is better to use the “in” operator rather than iterating over a list of strings

if you are a beginner, here is a link that can be useful to you
https://dynamopythonprimer.gitbook.io/dynamo-python-primer/

2 Likes